Skip to content

Instantly share code, notes, and snippets.

@vithonch
Created November 20, 2018 10:06
Show Gist options
  • Save vithonch/30874fcf033119bfff3a83739b9b1b69 to your computer and use it in GitHub Desktop.
Save vithonch/30874fcf033119bfff3a83739b9b1b69 to your computer and use it in GitHub Desktop.
/**
* Retries the given function until it succeeds given a number of retries and an interval between them. They are set
* by default to retry 5 times with 1sec in between. There's also a flag to make the cooldown time exponential
*/
async function retry(fn, retriesLeft = 5, interval = 1000, exponential = false) {
try {
const val = await fn();
return val;
} catch (error) {
if (retriesLeft) {
console.log(`Retrying in ${interval/1000} seconds... ${retriesLeft} retries left.`);
await new Promise(r => setTimeout(r, interval));
return retry(fn, retriesLeft - 1, exponential ? interval * 2 : interval, exponential);
} else throw new Error('Max retries reached');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment