JavaScript has a built-in function called setInterval that takes two arguments - a function, callback and an integer, timeout . When called, setInterval will call the function that you give it every timeout milliseconds.
For example, if you want to create a warning window every 500 milliseconds, you can do something like this.
function makeAlert(){ alert("Popup window!"); }; setInterval(makeAlert, 500);
However, you do not need to name your function or declare it separately. Instead, you can define an inline function, like so.
setInterval(function(){ alert("Popup window!"); }, 500);
After calling setInterval it will work until you call clearInterval for the return value. This means that the previous example will work endlessly. We can gather all this information together to create a progress bar that will be updated every second, and will stop updating after 10 seconds.
var timeleft = 10; var downloadTimer = setInterval(function(){ document.getElementById("progressBar").value = 10 - timeleft; timeleft -= 1; if(timeleft <= 0){ clearInterval(downloadTimer); } }, 1000);
<progress value="0" max="10" id="progressBar"></progress>
In addition, this will create a text countdown.
var timeleft = 10; var downloadTimer = setInterval(function(){ document.getElementById("countdown").innerHTML = timeleft + " seconds remaining"; timeleft -= 1; if(timeleft <= 0){ clearInterval(downloadTimer); document.getElementById("countdown").innerHTML = "Finished" } }, 1000);
<div id="countdown"></div>
source share