Created
February 17, 2020 21:21
-
-
Save hailwood/1d4353f0e3e26353c224c725a7a1d25b to your computer and use it in GitHub Desktop.
Promised Interval
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
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(); |
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
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