SetInterval is a very usefull function when making webpages that should look ‘alive’. I am here going to make a countdown timer using the setInterval and clearInterval functions:
First we need two variables:
var clock = 10; //Start value of counter var countdownId = 0; // Id of counter
Now we need the countdown function to call every interval:
function countdown() { if(clock > 0) { clock = clock - 1; document.getElementById('cdDiv').innerHTML = clock; } else { // Stop timer clearInterval(countdownId); } }
Now we need a div to show the timer in:
<div id="cdDiv">10</div>
Now we put it all togheter:
<html> <head> <title>My little countdown timer</title> <script type="text/javascript"> var clock = 10; var countdownId = 0; function start() { //Start clock countdownId = setInterval("countdown()", 1000); } function countdown(){ if(clock > 0){ clock = clock - 1; document.getElementById('cdDiv').innerHTML = clock; } else { //Stop clock clearInterval(countdownId); } } </script> </head> <body onload="start()"> <div id="cdDiv">10</div> </body> </html>
This small example is mostly so I remember the clearInterval function name which keeps escaping me 🙂
Very useful for my JS videogame, thank you 🙂
Glad I could help!
What is the purpose of assigning countdownID here:
countdownId = setInterval(“countdown()”, 1000);
I cant see why, and it runs fine with just:
setInterval(“countdown()”, 1000);
Cheers
Yes that is true. I just have as a practice to always save the interval id so that I can use it to remove the interval later
Ah i see, its assigned to a variable so we can identify it when we need to clear the interval. Sorry 🙂
It is a nice deisgn in a javascript.
link:https://www.nicesnippets.com/snippet/how-to-create-countdown-timer-and-clock-usign-javascript.