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;
var downloadTimer = setInterval(function(){
if(timeleft <= 0){
clearInterval(downloadTimer);
}
document.getElementById("progressBar").value = 10 - timeleft;
timeleft -= 1;
}, 1000);
<progress value="0" max="10" id="progressBar"></progress>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…