Thursday, December 25, 2008

Simple (and accurate) countdown timer in JS

Sample countdown timer:

The above example is a simple and straightforward implementation a javascript countdown timer to a future event. The script will use the computer's internal clock to calculate the time so it will be accurate no matter how long it runs (at least down to the second). The time is calculated using epoch time and the following calculation:

timeleft = targetepoch - currentepoch;

As you can see, the only requirements are that we know the target time and the current time. Current time is easy, and can be obtained using the following code:

var currentepoch = Math.floor(new Date().getTime()/1000);

The target time you either already have as input, or as in the example below, you calculate it based on the current time plus the remaining time. Here's the full body of the javascript method.

// the input time below is 1 day and 15 seconds var timeleft = 86415; // in seconds, this is the input time. var s; var m; var h; var d; var currentepoch = Math.floor(new Date().getTime()/1000); var targetepoch = currentepoch + timeleft; // this is when the timer runs out x=window.setTimeout("timerUpdate();", 1000); function timerUpdate() { currentepoch = Math.floor(new Date().getTime()/1000); timeleft = targetepoch - currentepoch; s = timeleft%60; if (s < 10) s = '0'+s; m = (timeleft-s)/60%60; if (m < 10) m = '0'+m; h = ((timeleft-s)/60 - m)/60%24; if (h < 10) h = '0'+h; d = (((timeleft-s)/60 - m)/60 - h)/24; if (d < 10) d = '0'+d; var txt = "" + d + ":" + h +":" + m +":" +s; document.getElementById("mytimer").innerHTML = txt; x=window.setTimeout("timerUpdate();", 1000); }

In the html document body I have defined a span of id "mytimer", and the javascript method displays the countdown timer as above.

I should note that this script has only been tested in Firefox, I don't know if it will work in other browsers. Also, please note the example has seconds resolution, not milliseconds (to get milliseconds, don't divide the epoch times by 1000). That's all, this script is simple, but that should now allow you to take it and improve it as you may see fit.

1 comment:

Anonymous said...

Thanks for the example. I had a timer script which was lagging in Firefox and not in Chrome and your script seems to work smoothly on both browsers. Thank you.