Created
April 19, 2011 15:39
-
-
Save chadgh/928500 to your computer and use it in GitHub Desktop.
A timer utility class for javascript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Timer(el, callbackFunction) { | |
// init the timer | |
// el - element for time to be updated | |
// callbackFunction - string of function name to | |
// be called when the countdown is finished. | |
this.init = function(el, callbackFunction) { | |
this.seconds = 0; | |
this.minutes = 0; | |
this.counterCaller = null; | |
this.timer = el; | |
this.doneCallback = callbackFunction; | |
this.running = true; | |
this.updateTimer(); | |
this.running = false; | |
this.isPaused = false; | |
} | |
// clears the timer - reset | |
this.clear = function() { | |
clearInterval(this.counterCaller); | |
this.isPaused = false; | |
this.seconds = 0; | |
this.minutes = 0; | |
} | |
// start a countdown for timerMinutes minutes and timerSeconds seconds | |
this.startTimer = function(timerMinutes, timerSeconds) { | |
this.clear(); | |
this.running = true; | |
this.seconds = timerSeconds; | |
this.minutes = timerMinutes; | |
this.updateTimer(); | |
var t = this; | |
this.counterCaller = setInterval(function() {t.countDown();}, 1000); | |
} | |
// pauses the countdown. | |
this.pauseTimer = function() { | |
if (this.isPaused) { | |
this.isPaused = false; | |
this.running = true; | |
var t = this; | |
this.counterCaller = setInterval(function() {t.countDown();}, 1000); | |
} else if (this.running) { | |
this.isPaused = true; | |
this.running = false; | |
clearInterval(this.counterCaller); | |
} | |
} | |
// countdown timer - alternatively could implement a countup timer | |
this.countDown = function() { | |
this.seconds--; | |
if (this.seconds < 0 && this.minutes != 0) { | |
this.seconds = 59; | |
this.minutes--; | |
} | |
if (this.minutes == 0 && this.seconds == 0) { | |
this.running = false; | |
} | |
this.updateTimer(); | |
} | |
// calls the callback function when countdown is complete. | |
this.notify = function() { | |
eval(this.doneCallback+"();"); | |
} | |
// updates the element content with the new time. | |
this.updateTimer = function() { | |
displaySeconds = this.seconds + ''; | |
displayMinutes = this.minutes + ''; | |
if (displaySeconds.length < 2) { | |
displaySeconds = "0" + displaySeconds; | |
} | |
if (displayMinutes.length < 2) { | |
displayMinutes = "0" + displayMinutes; | |
} | |
newTime = displayMinutes + ":" + displaySeconds; | |
this.timer.innerHTML = newTime; | |
if (!this.running) { | |
this.clear(); | |
this.notify(); | |
} | |
} | |
// instantiates a new timer. | |
this.init(el, callbackFunction); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment