Created
January 24, 2013 19:17
-
-
Save mattlo/4626650 to your computer and use it in GitHub Desktop.
Timer class
This file contains 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
/** | |
* @class Timer | |
*/ | |
NS('util').Timer = Class.extend(function () { | |
'use strict'; | |
return { | |
/** | |
* @construct | |
* @param {number} interval Number of milliseconds between each iteration | |
* @param {boolean} singleUse Determines to fire one or many iterations | |
*/ | |
init: function (interval, singleUse) { | |
this.interval = interval; | |
this.singleUse = singleUse; | |
this.session = null; // stores Interval session | |
this.tickAction = function () {}; // stores executable code as a functional expression | |
}, | |
/** | |
* Starts iteration | |
* @return {undefined} | |
*/ | |
start: function () { | |
if (this.singleUse === true) { | |
// single iteration | |
this.session = setTimeout(this.tickAction, this.interval); | |
} else { | |
// multiple iterations | |
this.session = setInterval(this.tickAction, this.interval); | |
} | |
}, | |
/** | |
* Stop iteration | |
* @param {boolean} invokeLastTickAction Fires last tick if set to true | |
* @return {undefined} | |
*/ | |
stop: function (invokeLastTickAction) { | |
// set default | |
invokeLastTickAction = invokeLastTickAction || false; | |
// stop timer session | |
clearInterval(this.session); | |
// optional fire | |
if (invokeLastTickAction === true) { | |
this.tickAction(); | |
} | |
}, | |
/** | |
* Event that is invokved per iteration | |
* @param {Function} | |
* @return {undefined} | |
*/ | |
setTickAction: function (setTickAction) { | |
this.tickAction = setTickAction; | |
} | |
}; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment