Search code examples
javascripttimercountdown

countdown timer in javascript


Possible Duplicate:
How to create a JQuery Clock / Timer

Does anyone knows countdown timer using javascript??


Solution

  • Using pure javascript, you would use the setTimeout method in a manner similar to this (treat this code as pseudocode, it is just to show the concept, I do not think it will work as-is):

    countdown = function()
    {
       var current = parseInt(document.getElementById("countdownBox").innerHTML);
       document.getElementById("countdownSpan").innerHTML = current;
    
       if (current > 0)
       {
           setTimeout('countdown()', 1000); // run every second
       }
    }
    

    You would start the countdown by writing something in the element with id countdownBox and calling countdown() for the first time.

    Edit: note that the setTimeout method will tend to lose seconds if used this way - if you want real precision you will most likely have to synchronize externally every once in a while.