Create a simple 10 second countdown

Joseph Christian Hefley picture Joseph Christian Hefley · Jun 29, 2015 · Viewed 154k times · Source

I would like a line that says:

Your download will begin in (10, 9, 8, etc. Beginning on page load) seconds.

I already have the 10 second download text set up, and I have looked at other stackoverflow posts. They all include CSS, and Jquery. I would like just a Javascript/HTML timer.

No other requests have been made for a simple line stating "You're download will begin in x seconds". How would I do this?

Answer

James McDowell picture James McDowell · Jun 29, 2015

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>

Alternatively, this will create a text countdown.

var timeleft = 10;
var downloadTimer = setInterval(function(){
  if(timeleft <= 0){
    clearInterval(downloadTimer);
    document.getElementById("countdown").innerHTML = "Finished";
  } else {
    document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
  }
  timeleft -= 1;
}, 1000);
<div id="countdown"></div>