There are two methods to implement countdown timers in JavaScript: setInterval(): Create a timer and call the function repeatedly every specified milliseconds. setTimeout(): Call the function only once, delaying the specified time.
Implementation of countdown timer in JS
In JavaScript, there are several ways to implement countdown timer. The following two methods are commonly used:
1. setInterval() method
setInterval()
method creates a timer that specifies The number of milliseconds to repeatedly call a function. To implement a countdown timer using the setInterval()
method, follow these steps:
setInterval()
method to call the update function every certain number of milliseconds. 2. setTimeout() method
setTimeout()
method only calls the function once, delaying the specified time. To implement a countdown timer using the setTimeout()
method, follow these steps:
setTimeout()
method to call this function after the remaining time. Sample code (setInterval() method)
<code>function updateCountdown() { const targetTime = new Date('2023-12-31'); const currentTime = new Date(); const msToTarget = targetTime - currentTime; const msToHours = Math.floor(msToTarget / (1000 * 60 * 60)); const msToMinutes = Math.floor(msToTarget / (1000 * 60)) % 60; const msToSeconds = Math.floor(msToTarget / 1000) % 60; const countdownDisplay = document.getElementById('countdown'); countdownDisplay.innerHTML = `${msToHours}:${msToMinutes}:${msToSeconds}`; if (msToTarget <= 0) { clearInterval(timeoutID); } } const timeoutID = setInterval(updateCountdown, 1000);</code>
Sample code (setTimeout() method)
<code>function countdown(ms) { const targetTime = Date.now() + ms; const countdownDisplay = document.getElementById('countdown'); const update = () => { const msRemaining = targetTime - Date.now(); if (msRemaining <= 0) { return; } const msToHours = Math.floor(msRemaining / (1000 * 60 * 60)); const msToMinutes = Math.floor(msRemaining / (1000 * 60)) % 60; const msToSeconds = Math.floor(msRemaining / 1000) % 60; countdownDisplay.innerHTML = `${msToHours}:${msToMinutes}:${msToSeconds}`; setTimeout(update, 1000); } update(); } countdown(3600000); // 1 小时</code>
The above is the detailed content of How to implement countdown timer in js. For more information, please follow other related articles on the PHP Chinese website!