Created
May 14, 2022 10:15
-
-
Save sidola/42c2f48a7bde5e3bb80663519ec125cf to your computer and use it in GitHub Desktop.
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
/** | |
* Calls the given list of promises in sequence, ensuring a minimum | |
* delay of `staggerMs` between calls. | |
* | |
* @param funcs Array of promises to call. | |
* @param staggerMs The minimum time between promise calls. If a | |
* promise runs longer than this, the next one is fired as soon as the | |
* previous is done. | |
*/ | |
export async function staggerCalls(funcs: (() => Promise<any>)[], staggerMs: number) { | |
for (let index = 0; index < funcs.length; index++) { | |
const element = funcs[index] | |
const start = Date.now() | |
await element() | |
// Delay next iteration | |
if (Date.now() - start < staggerMs) { | |
const delayFor = staggerMs - (Date.now() - start) | |
await new Promise(resolve => setTimeout(resolve, delayFor)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment