Skip to content

Instantly share code, notes, and snippets.

@phucat
Created July 3, 2013 06:49
Show Gist options
  • Save phucat/5915934 to your computer and use it in GitHub Desktop.
Save phucat/5915934 to your computer and use it in GitHub Desktop.
Global Timer for Javascript
/*
* Name : Global Timer Script
* By: Sugar Ray Tenorio ([email protected])
* 8/12/2012 1:01 AM
* dependencies : jQuery, Main Component
* http://www.javascriptph.com
********************************
adding functions in Timer
USAGE :
var alertMeEveryTenSeconds = {
'id' : 'test10',
interval : 10000,
params : 'test mike',
exec : function(msg) {
// CODE TO EXECUTE
}
}
timer._add(alertMeEveryTenSeconds);
********************************
killing / removing your functions
USAGE :
timer._remove('FUNCTION ID HERE');
*/
AB.addComponent('timer', {
interval: null,
_functions: {},
init: function (AB) {
var _parent = this;
this.interval = setInterval(function () {
$.each(_parent._functions, function () {
var _func = _parent._functions[this.id];
try {
if (!_func.original) _func.original = _func.interval;
if (_func.interval == 0) {
_func.exec(_func.params)
//AB.defer._add(_func.func, _func.param1, _func.param2);
_func.interval = _func.original;
} else {
_func.interval = _func.interval - 1000;
}
} catch (e) {
//alert(e);
}
});
}, 1000);
},
_add: function (func) {
this._functions[func.id];
var ptype = func;
// jslint complaints ab out the below line, but this is fine
var F = function () { };
F.prototype = ptype;
this._functions[func.id] = new F();
},
_remove: function (func) {
var id = (func.id) ? func.id : func;
this._functions[id] = null;
},
_stop: function () {
clearInterval(this.interval);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment