Skip to content

Instantly share code, notes, and snippets.

@sergeych
Created April 8, 2011 08:48
Show Gist options
  • Save sergeych/909511 to your computer and use it in GitHub Desktop.
Save sergeych/909511 to your computer and use it in GitHub Desktop.
Simple handy timer for jquery core.
function Timer(millis, callback, _params) {
var params = $.extend({repeat: false,context: this},_params)
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();
clog('aft!!',this)
if(this.repeat)
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, params, callback) {
if( !callback ) {
callback = params;
params = {};
}
this.timer = params.timer = new Timer(period, callback, $.extend(params,{context: this, args: params}));
params.timer.start();
return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment