JavaScript has built in to it a function called setInterval
, which takes two arguments - a function, callback
and an integer, timeout
. When called, setInterval
will call the function you give it every timeout
milliseconds.
For example, if you wanted to make an alert window every 500 milliseconds, you could do something like this.
function makeAlert(){
alert("Popup window!");
};
setInterval(makeAlert, 500);
However, you don't have to name your function or declare it separately. Instead, you could define your function inline, like this.
setInterval(function(){ alert("Popup window!"); }, 500);
Once setInterval
is called, it will run until you call clearInterval
on the return value. This means that the previous example would just run infinitely. We can put all of this information together to make a progress bar that will update every second and after 10 seconds, stop updating.
var timeleft = 10;_x000D_
var downloadTimer = setInterval(function(){_x000D_
if(timeleft <= 0){_x000D_
clearInterval(downloadTimer);_x000D_
}_x000D_
document.getElementById("progressBar").value = 10 - timeleft;_x000D_
timeleft -= 1;_x000D_
}, 1000);
_x000D_
<progress value="0" max="10" id="progressBar"></progress>
_x000D_
Alternatively, this will create a text countdown.
var timeleft = 10;_x000D_
var downloadTimer = setInterval(function(){_x000D_
if(timeleft <= 0){_x000D_
clearInterval(downloadTimer);_x000D_
document.getElementById("countdown").innerHTML = "Finished";_x000D_
} else {_x000D_
document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";_x000D_
}_x000D_
timeleft -= 1;_x000D_
}, 1000);
_x000D_
<div id="countdown"></div>
_x000D_