Monday 15 April 2013

How to create countdown timer using javascript

today i want to post article about how to create timer using purely javascript code..
the question ? how to manipulate the dom with javascript..

this is the answer. :

1. write on your html page <div id="timer"></div>   it would be the container of timer.

2. on your javascript write this code,




var counter = 10;
timer();
function timer(){
        if(counter>=0)
        {
            document.getElementById("timer").innerHTML = counter;
            counter -= 1;
            setTimeout(function(){timer()},1000);
        }
        else
        {
            //do something whatever
        }
}

i want to u know what exactly the code do, the point is :
1.  in function timer, in the first line statement contain  if(counter>=0) , this code is checking whether the variable counter is bigger or same with zero, if the condition is true it would be create a value counter on document which has id timer.
2. After that the code counter -= 1; it is just to decrement value counter to -1,
3. SetTimeout(function(){timer()},1000);  which call  function timer after 1000 milisecond or same as 1second.
4. timer function will be repeated until varible counter has value 0,
5. you can change how long the timer works with change the value of variable counter.

regards, ebuh bagiarta. #newbie-share

No comments:

Post a Comment