Created
December 3, 2020 21:05
-
-
Save Oaphi/c3f96f193a6eae8a243c0ff8a7aed67b to your computer and use it in GitHub Desktop.
Promise-based interval runner (cancellable)
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 withInterval = async ({ | |
timeouts = [], | |
delay = 0, | |
interval = 4, | |
callback, | |
times = 1, | |
stopIf = () => false | |
}) => { | |
if (!times) { | |
return; | |
} | |
if (delay) { | |
await new Promise((res) => setTimeout(res, delay)); | |
} | |
if (typeof callback !== "function") { return; } | |
const result = await callback(); | |
if (stopIf(result)) { | |
return result; | |
} | |
return new Promise((res, rej) => { | |
const timesLeft = times - 1; | |
const newId = setTimeout( | |
() => withInterval({ | |
timeouts, | |
delay, | |
interval, | |
callback, | |
times: timesLeft, | |
stopIf | |
}).then((output) => { | |
timeouts.splice(timeouts.indexOf(newId), 1); | |
res(output); | |
}).catch(rej), | |
interval); | |
timeouts.push(newId); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment