Skip to content

Instantly share code, notes, and snippets.

@ricardoalcocer
Created November 13, 2013 03:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ricardoalcocer/7443122 to your computer and use it in GitHub Desktop.
Save ricardoalcocer/7443122 to your computer and use it in GitHub Desktop.
Generic countdown timer
// implements a reusable countdown timer
// arguments:
// upper : upper limit to start countdown at
// onStart : function to execute when the timer starts
// onInterval : function to execute every second, like update screen
// onComplete : function to execute when the timer reaches 0
// onKill : function to execute when the timer is manually killed
function countdownTimer(upper,onStart,onInterval,onComplete,onKill){
var interval;
this.interval=interval;
this.upper=upper;
this.iterator=upper;
this.onStart=onStart;
this.onInterval=onInterval;
this.onComplete=onComplete;
this.onKill=onKill;
}
countdownTimer.prototype.kill=function(){
that=this;
clearInterval(that.interval); // stop this interval
that.onKill(); // call onKill
}
countdownTimer.prototype.start=function(){
var that=this;
that.onStart(); // call onstart
that.iterator=that.upper; // set upper boundary
that.onInterval(that.iterator); // call onInterval
that.interval=setInterval(timer, 1000); // start timer
function timer(){
that.iterator--; // decrement
that.onInterval(that.iterator); // call onInterval
if (that.iterator === 0){ // if this is the end
that.onComplete(); // call onComplete
clearInterval(that.interval); // stop this interval
}
}
}
exports.countdownTimer=countdownTimer;
@jhaynie
Copy link

jhaynie commented Apr 15, 2014

might want to make https://gist.github.com/ricardoalcocer/7443122#file-timer-js-L21 a local variable instead of a global (add var)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment