Created
October 18, 2017 00:55
-
-
Save LiamKarlMitchell/29aad3aa4db32dd37a6aa74ad0827eb4 to your computer and use it in GitHub Desktop.
JavaScript Interval timer
This file contains hidden or 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
/* | |
* 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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based from the stackoverflow solutions here: https://stackoverflow.com/questions/19088040/how-can-i-run-a-function-at-specific-time-date#comment28224988_19089196