Skip to content

Instantly share code, notes, and snippets.

@furf
Created April 15, 2009 22:10
Show Gist options
  • Save furf/96059 to your computer and use it in GitHub Desktop.
Save furf/96059 to your computer and use it in GitHub Desktop.
/**
* @class PeriodicalExecuter
* @param {Function} callback
* @param {Number} interval
* @param {Boolean} defer
* @constructs
*/
var PeriodicalExecuter = function(callback, interval, defer) {
this.callback = callback;
this.interval = interval;
this._timer = null;
this._lastExecutionTime = null;
this._nextExecutionTime = null;
if (!defer) {
this.start();
}
};
PeriodicalExecuter.prototype = {
_getCurrentTime: function() {
return (new Date()).getTime();
},
/**
* Sets the interval (in milliseconds) between callback executions. If the
* PeriodicalExecuter is running, it will restart using the new interval.
*/
setInterval: function(interval) {
this.interval = interval;
if (this.isExecuting()) {
this.restart();
}
},
getInterval: function() {
return this.interval;
},
isExecuting: function() {
return !!this._timer;
},
getTimeUntilNextExecution: function() {
if (this.isExecuting() && this._nextExecutionTime !== null) {
return this._nextExecutionTime - this._getCurrentTime();
} else {
return null;
}
},
_execute: function() {
this._lastExecutionTime = this._getCurrentTime();
this._nextExecutionTime = this._lastExecutionTime + this.interval;
this.execute();
},
execute: function() {
this.callback();
},
start: function() {
if (!this.isExecuting()) {
this._nextExecutionTime = this._getCurrentTime() + this.interval;
this._timer = setInterval(bind(this._execute, this), this.interval);
}
},
stop: function() {
if (this.isExecuting()) {
this._timer = clearInterval(this._timer);
this._lastExecutionTime = null;
this._nextExecutionTime = null;
}
},
restart: function() {
this.stop();
this.start();
}
};
/**
* @class PeriodicalExecuter
* @param {Function} callback
* @param {Number} interval
* @param {Boolean} defer
* @constructs
*/
var PeriodicalExecuter = function(callback, interval, defer) {
this.callback = callback;
this.interval = interval;
this._timer = null;
if (!defer) {
this.start();
}
};
PeriodicalExecuter.prototype = {
/**
* Sets the interval (in milliseconds) between callback executions. If the
* PeriodicalExecuter is running, it will restart using the new interval.
*/
setInterval: function(interval) {
this.interval = interval;
if (this._timer) {
this.stop();
this.start();
}
},
getInterval: function() {
return this.interval;
},
start: function() {
if (!this._timer) {
this._timer = setInterval(bind(this.execute, this), this.interval);
}
},
execute: function() {
this._timer
this.callback();
},
stop: function() {
if (this._timer) {
this._timer = clearInterval(this._timer);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment