![](/img/trans.png)
[英]Need help using an if else statement and a loop together. JavaScript
[英]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.