簡體   English   中英

需要幫助使用 JavaScript 中的“For”語句編寫循環代碼

[英]Need Help Coding a Loop Using "For" Statement in JavaScript

我需要使用循環從 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>

使用setTimeout重復調用 function 直到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();
 <div></div>

附加文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM