Skip to content

Instantly share code, notes, and snippets.

@4skinSkywalker
Created October 2, 2021 16:00
Show Gist options
  • Save 4skinSkywalker/979da8bc1f9bb1183e0ca55f7574f8cd to your computer and use it in GitHub Desktop.
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 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