Skip to content

Instantly share code, notes, and snippets.

@jasonbellamy
Created November 13, 2012 16:12
Show Gist options
  • Save jasonbellamy/4066683 to your computer and use it in GitHub Desktop.
Save jasonbellamy/4066683 to your computer and use it in GitHub Desktop.
Simple timed event manager
/**
* Handles set up / clean up of multiple named event timers
* @constructor
*/
var TimedEventManager = function () {
this.timers = {};
};
TimedEventManager.prototype = {
/**
* Creates a new timer
* @param {String} name the name of the timer
* @param {Number} duration the duration to wait before the timer is fired again
* @param {Function} callback the method to be run at the specified interval
*/
setTimer: function( name, duration, callback ) {
if ( !this.timers.hasOwnProperty(name) ) {
this.timers[name] = setInterval( callback, duration );
}
},
/**
* Gets an id that references the requested timer
* @param {String} name the name of the timer
* @return {Number} the id of the requested timer
*/
getTimer: function( name ) {
return this.timers[name];
},
/**
* Gets a list of all active timers
* @return {Object} hash of all active timers
*/
getTimers: function () {
return this.timers;
},
/**
* Stops and deletes a specified timer
* @param {String} the name of the timer to stop and delete
*/
deleteTimer: function( name ) {
if ( this.timers.hasOwnProperty(name) ) {
clearInterval( this.timers[name] );
delete this.timers[name];
}
},
/**
* Stops and deletes all active timers
*/
deleteTimers: function () {
for( var timer in this.timers ) {
if ( this.timers.hasOwnProperty(timer) ) {
this.deleteTimer( timer );
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment