Created
January 17, 2013 00:57
-
-
Save atinux/4552566 to your computer and use it in GitHub Desktop.
Super countdown with jQuery.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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