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); }