Skip to content

Instantly share code, notes, and snippets.

@LiamKarlMitchell
Created October 18, 2017 00:55
Show Gist options
  • Save LiamKarlMitchell/29aad3aa4db32dd37a6aa74ad0827eb4 to your computer and use it in GitHub Desktop.
Save LiamKarlMitchell/29aad3aa4db32dd37a6aa74ad0827eb4 to your computer and use it in GitHub Desktop.
JavaScript Interval timer
/*
* A timer that attempts to be more accurate than native setInterval.
* It calculates an appropriate delay to timeout after the callback is called.
* It is intended that the Callback function return ASAP this will not handle async operations that may be delayed.
*/
class Interval {
constructor(cb, ms) {
this.cb = cb;
this.ms = ms;
this.timeout = null;
}
start(callNow) {
// Already initialized.
if (this.timeout) {
return;
}
var loop = () => {
this.cb();
var now = new Date(); // allow for time passing
var delay = this.ms - (now % this.ms); // exact ms to next interval
this.timeout = setTimeout(loop, delay);
};
if (callNow) {
this.cb();
}
var now = new Date(); // allow for time passing
var delay = this.ms - (now % this.ms); // exact ms to next interval
this.timeout = setTimeout(loop, delay);
}
stop() {
clearTimeout(this.timeout);
}
}
@LiamKarlMitchell
Copy link
Author

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