Skip to content

Instantly share code, notes, and snippets.

@yuval-a
Last active April 15, 2018 15:33
Show Gist options
  • Save yuval-a/2a6a67bf8fea492ff9e2e41aa1bbb344 to your computer and use it in GitHub Desktop.
Save yuval-a/2a6a67bf8fea492ff9e2e41aa1bbb344 to your computer and use it in GitHub Desktop.
// A quick Javascript class for creating a countdown timer
// leadingZero is a boolean, onTimeCallback will be called on each second update with the timer string
function Countdown(hours,minutes,seconds, leadingZero, onTimeCallback) {
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
this.countdownStr = hours+":"+minutes+":"+seconds;
this.onTime = onTimeCallback;
this.leadingZero = leadingZero;
}
Countdown.prototype.start = function() {
this.countdownInterval = setInterval(function() {
this.seconds--;
if (this.seconds==-1) {
this.seconds = 59;
this.minutes--;
if (this.minutes==-1) {
this.minutes = 59;
this.hours--;
if (this.hours==-1) {
this.stop();
}
}
}
if (this.leadingZero) {
this.countdownStr = (this.hours<10?"0"+this.hours:this.hours) + ":" + (this.minutes<10?"0"+this.minutes:this.minutes) + ":" + (this.seconds<10?"0"+this.seconds:this.seconds);
}
else {
this.countdownStr = this.hours+":"+this.minutes+":"+this.seconds;
}
this.onTime(this.countdownStr);
}.bind(this), 1000);
}
Countdown.prototype.stop = function() {
if (this.countdownInterval) clearInterval(this.countdownInterval);
}
/* Example use. prepare a div: <div id="countdown"></div> */
// var cd = document.getElementById('countdown');
// var countdown = new Countdown(5,11,17, true, function(timestr) { cd.textContent = timestr; } );
// countdown.start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment