Skip to content

Instantly share code, notes, and snippets.

@qar
Created June 18, 2015 05:49
Show Gist options
  • Save qar/a95ba72d05c55ac45e98 to your computer and use it in GitHub Desktop.
Save qar/a95ba72d05c55ac45e98 to your computer and use it in GitHub Desktop.
count down
function countDown(duration, display) {
var M = 60;
var H = 60 * M;
var D = 24 * H;
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
days = (diff / D) | 0;
hours = ((diff % D) / H) | 0;
minutes = ((diff % H) / M) | 0;
seconds = (diff % M) | 0;
display({
d: days,
h: hours,
m: minutes,
s: seconds
});
if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
}
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment