Skip to content

Instantly share code, notes, and snippets.

@VassilisPallas
Created March 24, 2019 19:25
Show Gist options
  • Save VassilisPallas/edc38a3e9489042e86c413241c0d9819 to your computer and use it in GitHub Desktop.
Save VassilisPallas/edc38a3e9489042e86c413241c0d9819 to your computer and use it in GitHub Desktop.
Simple countdown timer without the usage of setInterval
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay) ;
}
function convertTime(hours) {
var realHours = Math.floor(hours);
var minutes = (hours - realHours) * 60;
var realMinutes = Math.round(minutes);
var realSeconds = ((hours - realHours) + (minutes - realMinutes)) * 60;
var seconds = Math.round(realSeconds);
if (seconds > 60) {
realMinutes++;
seconds -= 60;
}
return {hours: realHours, minutes: realMinutes, seconds: seconds}
}
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
function printHours(hours, minutes, seconds) {
return zeroPad(hours, 2) + ':' + zeroPad(minutes, 2) + ':' + zeroPad(seconds, 2);
}
function countDown(date, cb) {
var now = new Date().getTime();
if (now > date) {
throw new Error('date is old');
}
var totalHours = Math.abs(now - date) / 3600000;
var timeObj = convertTime(totalHours);
var hours = timeObj.hours;
var minutes = timeObj.minutes;
var seconds = timeObj.seconds;
cb(hours, minutes, seconds);
while (hours > 0 || minutes > 0 || seconds > 0) {
sleep(1000);
seconds--;
if (hours > 0 || minutes >= 0 || seconds >= 0) {
if (hours > 0 && minutes === 0 && seconds < 0) {
hours--;
minutes = 59;
seconds = 59;
} else if (minutes > 0 && seconds < 0) {
seconds = 59;
minutes--;
} else if ((hours > 0 || minutes > 0) && seconds < 0) {
seconds = 59;
}
}
cb(hours, minutes, seconds);
}
}
try {
var date = Date.parse("2019-03-25T17:00:00");
countDown(date, function (hours, minutes, seconds) {
console.log(printHours(hours, minutes, seconds));
});
console.log('countdown ended!')
} catch (e) {
console.log(e);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment