Code for a simple JavaScript countdown timer?

Mike picture Mike · Jul 28, 2009 · Viewed 309.9k times · Source

I want to use a simple countdown timer starting at 30 seconds from when the function is run and ending at 0. No milliseconds. How can it be coded?

Answer

Click Upvote picture Click Upvote · Jul 28, 2009
var count=30;

var counter=setInterval(timer, 1000); //1000 will  run it every 1 second

function timer()
{
  count=count-1;
  if (count <= 0)
  {
     clearInterval(counter);
     //counter ended, do something here
     return;
  }

  //Do code for showing the number of seconds here
}

To make the code for the timer appear in a paragraph (or anywhere else on the page), just put the line:

<span id="timer"></span>

where you want the seconds to appear. Then insert the following line in your timer() function, so it looks like this:

function timer()
{
  count=count-1;
  if (count <= 0)
  {
     clearInterval(counter);
     return;
  }

 document.getElementById("timer").innerHTML=count + " secs"; // watch for spelling
}