[英]javascript countdown timer issue when using setTimeout()
倒數計時器不會加載 - 僅在頁面刷新后。
我已經在 codepen.io 等上測試了代碼,但是當托管在網站上時,倒計時不會出現,只有在刷新后才會出現。
當我使用setInterval()
它工作正常,但是我想只更新一次倒計時,因為它是天倒計時,因此使用了setTimeout()
。
// Set the date we're counting down to var countDownDate = new Date("Sep 5, 2018 15:37:25").getTime(); // Update the count down every 1 second var x = setTimeout(function() { // Get date var now = new Date().getTime(); // Find the distance between now an the count down date var distance = countDownDate - now; // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); // Output the result in an element with id="demo" document.getElementById("demo").innerHTML = days + " days left "; // If the count down is over, write some text if (distance < 0) { clearTimeout(x); document.getElementById("demo").innerHTML = "EXPIRED"; } }, 300);
完整代碼: https : //codepen.io/anon/pen/VQzMdG
您可以創建一個data-attribute
,即: updateCountdown
。 那將是只更新倒計時一次的標志。
// Set the date we're counting down to var countDownDate = new Date("Sep 5, 2018 15:37:25").getTime(); // Update the count down every 1 second var x = setInterval(function() { // Get date var now = new Date().getTime(); // Find the distance between now an the count down date var distance = countDownDate - now; // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var demo = document.getElementById("demo"); if (!demo.dataset.updateCountdown) { console.log('Update countdown.'); demo.dataset.updateCountdown = false; // Output the result in an element with id="demo" demo.innerHTML = days + " days left "; } console.log(x) // If the count down is over, write some text if (distance < 0) { clearInterval(x); document.getElementById("demo").innerHTML = "EXPIRED"; } }, 2000);
<span id='demo'></span>
看? 現在它只更新了一次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.