Skip to content

Instantly share code, notes, and snippets.

@sidola
Created May 14, 2022 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sidola/42c2f48a7bde5e3bb80663519ec125cf to your computer and use it in GitHub Desktop.
Save sidola/42c2f48a7bde5e3bb80663519ec125cf to your computer and use it in GitHub Desktop.
/**
* 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