Skip to content

Instantly share code, notes, and snippets.

@bearzk
Created September 18, 2020 09:01
Show Gist options
  • Save bearzk/a8d1c1903bb359f45e56a9e15f8111b6 to your computer and use it in GitHub Desktop.
Save bearzk/a8d1c1903bb359f45e56a9e15f8111b6 to your computer and use it in GitHub Desktop.
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const exponentialBackOff = async (func, maxRetry, delay) => {
let res = await func();
if (res) {
return res;
}
console.log(`retrying, maxRetry ${maxRetry}`);
if (0 < maxRetry) {
await sleep(delay);
return await exponentialBackOff(func, --maxRetry, delay * 2);
}
console.error('func call failed');
return null;
}
// try funcToRun 20 times max, start with 500ms delay in the first fail
const status = await exponentialBackOff(funcToRun, 20, 500);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment