Javascript Countdown Timer

Better code for doing a date-based countdown in Javascript. The top results on Google appear to have been written in 1990 and are unnecessarily cumbersome– here’s a version I wrote for a quick Christmas “countdown” webpage.

One major advantage to my version is that it compensates for the date in a given timezone, so that it counts down to the same exact second regardless of time zone (assuming that everyone’s computer time is accurate) instead of “rolling” across time zones. This is done by taking advantage of the way numerical timestamps are stored (always in GMT) and the .toUTCString commands. For an even more accurate rollout, I used inline php code to populate the timestamp number and also perform some logic when the server thinks the time has been reached, so that users can’t simply change their computer’s clock to see the result (which in this case is just reloading, since my PHP should have replaced the server-side HTML by that point.)

If you’d like to see the inline PHP that handles the official rollout, leave a comment!

<script type="text/javascript">// <![CDATA[
/* Javascript Countdown Timer
* Will Bradley ( Dec. 2009
* Code released publicly without any warranty or license.
function showtime() {
dateString = new Date().toUTCString();
now = Date.parse(dateString);
xmasDateString = new Date(1261724400000).toUTCString(); // The long number is December 25, 2009 in Javascript's .getTime() format. You can put almost any value in here, including plain english dates.
xmasDate = Date.parse(xmasDateString);
dd = xmasDate now;
if(now > xmasDate)
// Put any "countdown done!" code here. I've got it reloading in order to pull new info via a coordinated PHP countdown, but you could put anything.
document.getElementById("secs").innerHTML = "Reload the page for your gift!";
document.getElementById("secs").innerHTML =
dday + "<em>days</em>" +
dhour + "<em>hours</em>" +
dmin + "<em>minutes</em>" +
dsec + "<em>seconds</em>";
timerID = setTimeout("showtime()",1000);
// ]]></script>
<style type="text/css"><!
body { backgroundcolor: black; color: white; text-align: center;
font-family: Lucida Sans Unicode, Lucida Grande, sans-serif; font-size: 12px;
h1 { color: #ee0000; font-weight: bold; margin-top: 150px; font-size: 4em; text-transform: uppercase; }
h1 em { color: white; font-style: normal; margin: 0 0.5em 0 0.25em; font-size: 0.4em; }
<h1 id="secs"></h1>

view raw


hosted with ❤ by GitHub


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s