To make a countdown timer in JavaScript, decrease the seconds in
setInterval
, then output to a div
.For example, if this is your div
:
<div id="timer"></div>
Then you can make a 30-seconds countdown timer with this JavaScript:
window.addEventListener('DOMContentLoaded', () => {
let seconds = 30;
const intervalId = setInterval(() => {
document.getElementById('timer').textContent = `00:${seconds < 10 ? 0 : ''}${seconds}`;
if (--seconds < 0) {
clearInterval(intervalId);
}
}, 1_000);
});