I'm sure there are quite a few of these out there, but after a little searching I didn't find one - well, at least I didn't find a good one, one that behaved like I wanted. I'm sure we've all seen 'em, and some are quite a bit fancier that others, but I wanted to write a quick javascript that I could throw on a web page and get your basic 'countdown' functionality.
I desired to make the code semi-reusable. That is, I didn't want the basic countdown functionality to be baked into the code, that way I could make the countdown arbitrary. The code is extremely simple and straightforward, but in an effort to preserve it and make it available to anyone who wants this kind of functionality, I present it here for you.
The code does have a few limitations that you might notice right off the bat. Most notably, and due to the way it is written, you can only ever have one countdown per page. This limitation isn't that severe, but if you for some reason needed two or more, the code would have to be altered. Also, I baked in some 'magic numbers' into the script. These numbers are in essence constants and I didn't see the need to recalculate them on every iteration, each time the countdown text is updated. [Updated 04/09//2006 - In reviewing the code, I meant to make the function calls Math.floor() rather than the parseInt() that I originally had - though they both have the same net result]
var _elem, _deadline, _doneHtml, _timer;
function startCountdown(elementId, deadline, doneHtml) {
_elem = document.getElementById(elementId);
_deadline = deadline;
_doneHtml = doneHtml;
_timer = setInterval("countdownTick()", 1000);
}
function countdownTick() {
var diff = _deadline - new Date();
if ( diff > 1000 ) {
var s = Math.floor(diff / 1000 % 60);
var m = Math.floor(diff / 60000 % 60); // 1000 * 60
var h = Math.floor(diff / 3600000 % 24); // 1000 * 60 * 60
var d = Math.floor(diff / 86400000); // 1000 * 60 * 60 * 24
_elem.innerHTML =
d.toString() + " day" + (( 1 == d ) ? " " : "s ") +
h.toString() + " hour" + (( 1 == h ) ? " " : "s ") +
m.toString() + " minute" + (( 1 == m ) ? " " : "s ") +
( ( 60 == s ) ? "0" : s.toString() ) + " second" + (( 1 == s ) ? "" : "s");
}
else {
_elem.innerHTML = _doneHtml;
clearInterval(_timer);
}
}
Simply call the startCountdown() function, providing the ID of the HTML element (such as a DIV, SPAN, P, etc) that will be the container for the countdown, the date (date and time) that the countdown expires, and the HTML text to render when the countdown expires. When the timer counts down to zero, the countdown will replace the text with the appropriate notification.
<div id=“countdown“></div>
<script>
startCountdown(“countdown“, new Date(2006, 0, 1, 0, 0, 0), “<b>Happy New Year!</b>“);
</script>