Skip to content

Instantly share code, notes, and snippets.

@hailwood
Created February 17, 2020 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hailwood/1d4353f0e3e26353c224c725a7a1d25b to your computer and use it in GitHub Desktop.
Save hailwood/1d4353f0e3e26353c224c725a7a1d25b to your computer and use it in GitHub Desktop.
Promised Interval
const interval = new PromisedInterval(async () => {
//Do something here
}, 5000);
// Start the loop running
interval.start(); // you can await this if you'd like to pause until something stops the interval
// Pause the execution after the current loop finishes
interval.stop();
// Change the loop timer
interval.setInterval(8000);
// Start the loop again
interval.start();
class PromisedInterval {
constructor(handler, interval) {
this.setHandler(handler);
this.setInterval(interval);
this.running = false;
}
setInterval(interval) {
this.interval = interval;
}
setHandler(handler) {
this.handler = handler;
}
async start() {
this.running = true;
while (this.running) {
await this.loop();
}
}
stop() {
this.running = false;
}
async loop() {
const runStartTimestamp = Date.now();
await this.handler();
const runDifference = Date.now() - runStartTimestamp;
const timeUntilNextLoop = this.interval - runDifference;
return new Promise(resolve => setTimeout(resolve, timeUntilNextLoop));
}
}
export default PromisedInterval;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment