Skip to content

Instantly share code, notes, and snippets.

@SaneMethod
Last active December 23, 2015 18:39
Show Gist options
  • Save SaneMethod/6677116 to your computer and use it in GitHub Desktop.
Save SaneMethod/6677116 to your computer and use it in GitHub Desktop.
(More) accurate timers for javascript.
(function(window){
window.performance = window.performance || {};
performance.now = performance.now || function(){
return +new Date();
};
function AccurateInterval(options){
this.startTime = 0;
this.elapsed = 0;
this.timeout = 0;
this.interval = options.interval || 100;
this.callback = options.callback;
if (typeof this.callback !== 'function') throw 'You must specify a callback function.';
return this;
}
AccurateInterval.prototype.start = function(){
this.startTime = performance.now();
this.timeout = window.setTimeout(this.tick.bind(this), this.interval);
return this;
};
AccurateInterval.prototype.tick = function(){
this.elapsed += this.interval;
var missedTicks = 0,
nextInterval = this.interval - ((performance.now() - this.startTime) - this.elapsed);
if (nextInterval <= 0) {
missedTicks = (Math.abs(nextInterval) / this.interval) | 0;
this.elapsed += missedTicks * this.interval;
this.tick();
return;
}
this.callback();
this.timeout = window.setTimeout(this.tick.bind(this), nextInterval);
};
AccurateInterval.prototype.stop = function(){
window.clearTimeout(this.timeout);
return this;
};
window.setAccurateInterval = function(callback, interval){
return new AccurateInterval({callback:callback, interval:interval}).start();
};
window.clearAccurateInterval = function(acc){
acc.stop();
};
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment