Skip to content

Instantly share code, notes, and snippets.

@hcortezr
Forked from manast/interval.js
Last active February 13, 2018 09:24
Show Gist options
  • Save hcortezr/4e0e11d09a8a7e0d8fce9e6b8c0c9385 to your computer and use it in GitHub Desktop.
Save hcortezr/4e0e11d09a8a7e0d8fce9e6b8c0c9385 to your computer and use it in GitHub Desktop.
Accurate Javascript setInterval replacement
let int = createInterval(() => console.log("Hello!"), 1000);
int.run();

setTimeout(() => int.stop(), 5000);
createInterval = function(fn, interval){
return new (function(){
this.baseline = undefined;
this.run = function(){
if(this.baseline === undefined){
this.baseline = Date.now();
}
fn();
let end = Date.now();
this.baseline += interval;
let nextTick = interval - (end - this.baseline);
if (nextTick < 0) nextTick = 0;
this.timer = setTimeout(() => this.run(end), nextTick);
};
this.stop = () => clearTimeout(this.timer);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment