Skip to content

Instantly share code, notes, and snippets.

@mattlo
Created January 24, 2013 19:17
Show Gist options
  • Save mattlo/4626650 to your computer and use it in GitHub Desktop.
Save mattlo/4626650 to your computer and use it in GitHub Desktop.
Timer class
/**
* @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