Skip to content

Instantly share code, notes, and snippets.

@atinux
Created January 17, 2013 00:57
Show Gist options
  • Save atinux/4552566 to your computer and use it in GitHub Desktop.
Save atinux/4552566 to your computer and use it in GitHub Desktop.
Super countdown with jQuery.
var countDown = function (endDate, el) {
el = el || $('body');
var leadingZero = function (nb) {
return (nb < 10) ? "0" + nb : + nb;
};
var updateTimer = function (seconds) {
var days = Math.floor(seconds / 86400);
seconds -= days * 86400;
var hours = Math.floor(seconds / 3600);
seconds -= hours * (3600);
var minutes = Math.floor(seconds / 60);
seconds -= minutes * (60);
return ((days > 0) ? days + " days " : "") + leadingZero(hours) + ":" + leadingZero(minutes) + ":" + leadingZero(seconds);
};
var tick = function () {
// Get seconds
var nbSeconds = parseInt((+endDate - +new Date) / 1000);
if (nbSeconds < 1) {
el.html('Time finished!');
return;
}
el.html(updateTimer(nbSeconds));
setTimeout(tick, 500);
};
tick();
};
@atinux
Copy link
Author

atinux commented Jan 17, 2013

Use cases:

countDown(new Date('2013-01-17 02:00:00')); will write the countdown in the body;

countDown(new Date('2013-01-17 02:00:00'), $('#countdown')); will write the countdown in the #countdown element.

Result:
1 days 23:59:38

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment