如何在 JavaScript 中設定倒計時器?
我們可以使用 setInterval() 方法在 JavaScript 中設定倒計時器。此方法會以每次呼叫之間固定的時間延遲不斷呼叫函式或執行程式碼片段。
setInterval() 方法以描述的間隔以毫秒為單位呼叫函式。它將繼續呼叫函式直到呼叫 clearInterval() 或關閉視窗。
語法
以下是此方法的語法 −
setInterval(function, milliseconds);
setInterval 方法接受兩個引數函式和毫秒。
函式 − 包含旨在執行特定任務的程式碼塊的函式。
毫秒 − 這是函式執行之間的間隔時間。
此方法將返回一個正整數,表示間隔 ID。
示例
在以下示例中,我們從 2027 年 1 月 1 日 12:12:50 建立一個倒計時器到當前時間。
<!DOCTYPE html> <html lang="en"> <head> <title>countDownTimer</title> <style> h3 { text-align: center; margin-top: 0px; } </style> </head> <body> <h3 id="time"></h3> <script> // set the date we are counting down to var countDown = new Date("jan 1, 2027 12:12:50").getTime(); //update the count down in every 1 second var update = setInterval(function () { // get the today's date and time var now = new Date().getTime(); //find the difference b/w countDown and now var diff = countDown - now; //now we are calculating time in days, hrs, minutes, and seconds. var days = Math.floor(diff / (1000 * 60 * 60 * 24)); var hrs = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((diff % (1000 * 60)) / 1000); //now output the result in an element with id ="time" document.getElementById("time").innerHTML = days + "-D: " + hrs + "-H: " + minutes + "-M: " + seconds + "-S "; if (diff < 0) { clearInterval(update); document.getElementById("time").innerHTML = "Expired"; } }, 1000); </script> </body> </html>
廣告