簡體   English   中英

JavaScript超時功能值未遞增

[英]Javascript timeout function value not incrementing

我正在嘗試使用setInterval函數來實現javascript超時功能,當我使用該函數時,我能夠顯示時間,計時器在遞減,但是每次我每次重新加載頁面時都需要重新加載。

timer.html

 function countTimer(countDownDate) { 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 hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); // Output the result in an element with id="demo" document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s "; // If the count down is over, write some text if (distance < 0) { clearInterval(x); document.getElementById("demo").innerHTML = "EXPIRED"; } } var countDownDate = new Date("Mar 12, 2017 15:37:25").getTime(); var x = countTimer(countDownDate) var y = setInterval(x, 1000); 
 p { text-align: center; font-size: 60px; } 
 <p id="demo"></p> 

輸出:

2d 2h 45m 37s

任何幫助,將不勝感激... :)在此先感謝

您沒有正確使用setInterval ,它接受設置延遲后要執行的字符串文字代碼或函數。

現在,您將undefined傳遞給它。 將您的代碼更改為

var y = setInterval(function () {
    var countDownDate = new Date("Mar 12, 2017 15:37:25").getTime();
    var x = countTimer(countDownDate)
}, 1000);

 function countTimer(countDownDate) { 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 hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); // Output the result in an element with id="demo" document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s "; // If the count down is over, write some text if (distance < 0) { clearInterval(x); document.getElementById("demo").innerHTML = "EXPIRED"; } } var y = setInterval(function() { var countDownDate = new Date("Mar 12, 2017 15:37:25").getTime(); var x = countTimer(countDownDate) }, 1000); 
 p { text-align: center; font-size: 60px; } 
 <p id="demo"></p> 

暫無
暫無

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

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