Created
October 2, 2021 16:00
-
-
Save 4skinSkywalker/979da8bc1f9bb1183e0ca55f7574f8cd to your computer and use it in GitHub Desktop.
This is like an interval but can be start/paused/resumed/forced and evaluates calls sequentially
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
// This function is just an arbitrary delay to be used with async/await pattern | |
export function delay(ms) { | |
return new Promise(res => | |
setTimeout(() => | |
res(1) | |
, ms) | |
); | |
} | |
/* SmartInterval creates an interval that has the following features: | |
* - Can be paused/stopped | |
* - Can be forced to execute | |
* - Evaluates sequentially (no other call is made before the current call is evaluated) | |
*/ | |
export function SmartInterval(asyncFn, delayMs) { | |
this.asyncFn = asyncFn; | |
this.delayMs = delayMs; | |
this.running = false; | |
} | |
SmartInterval.prototype.cycle = async function () { | |
await this.asyncFn(); | |
await delay(this.delayMs); | |
if (this.isRunning) this.cycle(); | |
}; | |
SmartInterval.prototype.start = function () { | |
if (this.isRunning) return; | |
this.isRunning = true; | |
this.cycle(); | |
}; | |
SmartInterval.prototype.stop = function () { | |
if (this.isRunning) this.isRunning = false; | |
}; | |
SmartInterval.prototype.forceExecution = function () { | |
this.cycle(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment