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";
}
}

Comments

Popular posts from this blog

Calling Conventions in Delphi: safecall vs stdcall vs cdecl

How to use TpFIBDataSet, TpFIBQuery and TpFIBTransaction FIBPlus components to connect with Firebird / Interebase database in Delphi XE4?

VCL Hierarchy in Delphi: Types of Controls in Delphi: TWinControls and TGraphicControls