Sunday, 20 October 2013

How to implement javascript count down timer using setInterval and clearInterval methods?

How to implement javascript count down timer using setInterval and clearInterval methods?

I had to implement  a count down timer in my project which runs for 40 seconds. I implemented count down timer in javascript using setInterval() and clearInterval() methods. I am sharing my javascript timer code in this post. It is very simple and can be understood in one go. Below is my javascript code snippet for count down timer.

        function playTimer()
        {
var count= 40;
document.getElementById("timer").innerHTML=count + " secs left";
var count_down=setInterval(timer, 1000); 
}

function timer()
{
count=count-1;
//if time is finished
if (count <= 0)
{
document.getElementById("timer").innerHTML="Time Over";
clearInterval(count_down);
                        //call you function which has to be called after timer
return;
}
//if 1 second is left, display "sec" instead of "secs"
if (count == 1)
{
document.getElementById("timer").innerHTML=count + " sec left";   
}
else
{
document.getElementById("timer").innerHTML=count + " secs left";
}
}

2 comments:

  1. I am not sure ifmit works. I have not run it but you have declared to variables local to playTimer (count and count_down) and they cannot be accessed from the second function timer

    ReplyDelete
  2. www.easyyar.com is a best jobs site, Search for Job Vacancies IT, Software, Govt., Technical and other jobs.Post your resume now and get your first dream job!

    http://www.easyyar.com

    ReplyDelete