Skip to content

Instantly share code, notes, and snippets.

@gengkev
Forked from manast/interval.js
Created December 28, 2011 15:26
Show Gist options
  • Save gengkev/1528336 to your computer and use it in GitHub Desktop.
Save gengkev/1528336 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);
};
@gengkev
Copy link
Author

gengkev commented Dec 28, 2011

This code is a fork of manast's. It's an improvement over setInterval() as it keeps an internal clock that uses new Date() to preecisely track when setTimeout is off and adjusts, so the average of the offsets from the duration will be as close to 0 as possible. At least on my computer, setInterval() actually deviates less as it doesn't try to adjust to be correct, but it will end up being a couple of seconds off after a number of repeats.

Usage:

var interval = new Interval(function() {
  // do something
},100); // or whatever time

// do something
interval.stop();

// you can do this if you like...
interval.run();

@gengkev
Copy link
Author

gengkev commented Dec 28, 2011

Something interesting...

var time = +new Date(),
  interval = new Interval(function() {
    var n = +new Date();
    console.log(n - time);
    time = n;
  },duration);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment