Skip to content

Instantly share code, notes, and snippets.

@djmadeira
Created June 16, 2015 15:37
Show Gist options
  • Save djmadeira/8b9d825ca98ed9997914 to your computer and use it in GitHub Desktop.
Save djmadeira/8b9d825ca98ed9997914 to your computer and use it in GitHub Desktop.
Simple countdown timer in JS
/**
* Don't put your vars in the global scope in production code,
* much less these tersely-named ones.
*/
var end = new Date('July 1, 2016 12:00:00');
var el;
// Seconds/minute, etc (in miliseconds)
var sm = 60 * 1000,
sh = 3600 * 1000,
sd = 86400 * 1000;
// Display numbers padded to a certain width
function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
// Element references are hard-coded; probably don't do this if you put this in production code
function updateTimer() {
var now = Date.now();
var then = end.getTime();
// Math.max is to prevent negative values, which messes up the math
var dleft = Math.max(Math.floor((then - now) / sd), 0);
var hleft = Math.max(Math.floor((then - (dleft * sd) - now) / sh), 0);
var mleft = Math.max(Math.floor((then - (dleft * sd + hleft * sh) - now) / sm), 0);
var sleft = Math.max(Math.floor((then - (dleft * sd + hleft * sh + mleft * sm) - now) / 1000), 0);
document.getElementById('dd').innerHTML = pad(dleft, 2);
document.getElementById('hh').innerHTML = pad(hleft, 2);
document.getElementById('mm').innerHTML = pad(mleft, 2);
document.getElementById('ss').innerHTML = pad(sleft, 2);
}
function timer() {
updateTimer();
setInterval(updateTimer, 1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment