Sometimes, we want to create a simple 10 second countdown with JavaScript.
In this article, we’ll look at how to create a simple 10 second countdown with JavaScript.
How to create a simple 10 second countdown with JavaScript?
To create a simple 10 second countdown with JavaScript, we use the setInterval
method.
For instance, we write
<progress value="0" max="10" id="progressBar"></progress>
to add a progress element.
Then we update it by writing
let timeleft = 10;
const downloadTimer = setInterval(() => {
if (timeleft <= 0) {
clearInterval(downloadTimer);
}
document.getElementById("progressBar").value = 10 - timeleft;
timeleft -= 1;
}, 1000);
to call setInterval
with a function that calls clearInterval
to stop the timer if timeLeft
is 0 or less.
Otherwise, we update the progress element with the value
of 10 - timeleft
to show the count down value.
And then we decrement timeLeft
by 1.
Conclusion
To create a simple 10 second countdown with JavaScript, we use the setInterval
method.