Skip to content

Instantly share code, notes, and snippets.

@matylla
Forked from gengkev/interval.js
Created February 22, 2012 09:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matylla/1883504 to your computer and use it in GitHub Desktop.
Save matylla/1883504 to your computer and use it in GitHub Desktop.
Accurate Javascript setInterval replacement
function Interval(func,duration){
if(typeof func !== "function") throw new TypeError("Expected function");
else if(typeof duration !== "number") throw new TypeError("Expected number");
this.func = func;
this.duration = duration;
this.baseline = +new Date();
(function(_this){
_this.timer = setTimeout(function(){
_this.run();
},duration);
})(this);
};
Interval.prototype.run = function(){
this.func.call(window);
this.baseline += this.duration;
var nextTick = this.duration + this.baseline - new Date();
if(nextTick<0) nextTick = 0;
(function(_this){
_this.timer = setTimeout(function(){
_this.run();
},nextTick);
})(this);
};
Interval.prototype.stop = function(){
clearTimeout(this.timer);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment