Skip to content

Instantly share code, notes, and snippets.

@shanecp
Created June 20, 2014 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shanecp/4329c063e85216268891 to your computer and use it in GitHub Desktop.
Save shanecp/4329c063e85216268891 to your computer and use it in GitHub Desktop.
JS Countdown timer
$(document).ready(function() {
window.offerTimer = {};
offerTimer.offerEndTime = new Date(0);
offerTimer.offerEndTime.setUTCSeconds(#getEpoch(offerEndTime)#);
function formatNumber(number) {
number = number.toString();
if (number.length === 1) {
return '0' + number;
} else {
return number;
}
}
function updateTimer() {
// start the countdown timer
var currentTime = new Date();
var secondsLeft = (currentTime - offerTimer.offerEndTime) / 1000;
if (secondsLeft < 0) {
secondsLeft = parseInt(secondsLeft, 10);
secondsLeft = Math.abs(secondsLeft);
var days = Math.floor(secondsLeft / 86400);
secondsLeft -= days * 86400;
var hours = Math.floor(secondsLeft / 3600);
secondsLeft -= hours * 3600;
var minutes = Math.floor(secondsLeft / 60);
var seconds = secondsLeft - minutes * 60;
if (days == 1) $('.days-label').text(' ' + days + ' day and');
if (days > 1) $('.days-label').text(' ' + days + ' days and');
$('.time-block.hours').text(formatNumber(hours));
$('.time-block.minutes').text(formatNumber(minutes));
$('.time-block.seconds').text(formatNumber(seconds));
// recursive update
setTimeout(updateTimer, 1000);
} else {
$('.countdown-timer').hide();
}
}
$('.countdown-timer').show();
updateTimer();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment