let int = createInterval(() => console.log("Hello!"), 1000);
int.run();
setTimeout(() => int.stop(), 5000);
-
-
Save hcortezr/4e0e11d09a8a7e0d8fce9e6b8c0c9385 to your computer and use it in GitHub Desktop.
Accurate Javascript setInterval replacement
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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