【问题标题】:Need Help Coding a Loop Using "For" Statement in JavaScript需要帮助在 JavaScript 中使用“For”语句编写循环代码
【发布时间】:2021-11-30 20:49:30
【问题描述】:

我需要使用循环从 10 到 0 进行倒计时。循环应该替换需要重复 10X 的代码。我还需要在 HTML 中向用户显示倒计时。救命!

<script>
       
function StartTheCountdown()
{ 
     var Countdown = 10;
     // Used to keep track of actual time.
     // 1000 = 1 second because we are using milliseconds.
    var timeout = 10000;
    setTimeout(() => {
    document.getElementById("CountDownDisplay").innerHTML = "Blastoff!";
    Countdown = Countdown - 1;
    }, timeout)
    timeout = timeout - 1000;
    // We need to do this 10 times **************************************
    setTimeout(() => {
    document.getElementById("CountDownDisplay").innerHTML = Countdown;
    Countdown = Countdown - 1;
    }, timeout)
    timeout = timeout - 1000; 
}
    </script>

【问题讨论】:

标签: javascript loops for-loop


【解决方案1】:

使用setTimeout重复调用函数,直到count为零,然后显示消息。

// Cache your element
const div = document.querySelector('div');

// Initialise your count to 10
function countdown(count = 10) {

  // Update your element textContent
  div.textContent = `T-minus: ${count}`;

  // Call the function again if the count
  // is greater than 0 with a decremented count
  if (count > 0) {
    setTimeout(countdown, 1000, --count);

  // Otherwise update the textContent of the
  // element with a message
  } else {
    div.textContent = 'Blast off!';
  }
}

countdown();
&lt;div&gt;&lt;/div&gt;

其他文档

【讨论】:

    猜你喜欢
    • 2016-06-14
    • 2019-11-23
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多