Skip to content

Instantly share code, notes, and snippets.

@logicaroma
Forked from sergeych/jqtimer.rb
Created April 8, 2011 08:52
Show Gist options
  • Save logicaroma/909516 to your computer and use it in GitHub Desktop.
Save logicaroma/909516 to your computer and use it in GitHub Desktop.
function Timer(millis, callback, _params) {
var params = $.extend(_params,{repeat: true,context: this})
this.interval = millis;
this.repeat = params.repeat;
this.context = params.context;
this.args = params.args;
this.onTimer = callback;
this.callback = $.proxy(this._onTimer, this);
this.single = false;
this._reqs = 0;
}
Timer.prototype._onTimer = function() {
this._timer = undefined;
this.invoke();
if(!this.single)
this._timer = setTimeout(this.callback,this.interval);
}
Timer.prototype.start = function() {
this.stop();
this._timer = setTimeout(this.callback,this.interval);
return this;
}
Timer.prototype.stop = function() {
if( this._timer) clearTimeout(this._timer);
this._timer = undefined;
return this;
}
Timer.prototype.invoke = function() {
clog(this._reqs,this._inside, !this._inside);
this._reqs ++;
try {
if( ! this._inside) {
this._inside = true;
do {
this.onTimer.apply(this.context, this.args)
} while( --this._reqs > 0)
this._inside = false;
}
}
catch(error) {
clog('ERROR: Timer invocation:', error);
}
}
$.fn.timer = function(period, data, callback) {
var event;
event.timer = new Timer(period, callback, {context: this, args: event});
event.data = data;
return event.timer.start();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment