Skip to content

Instantly share code, notes, and snippets.

@pedroraft
Created December 7, 2021 11:51
Show Gist options
  • Save pedroraft/25ad4ea5f42a1a12d1ca128266ea0a31 to your computer and use it in GitHub Desktop.
Save pedroraft/25ad4ea5f42a1a12d1ca128266ea0a31 to your computer and use it in GitHub Desktop.
typescript exponential backoff
const delay = (retryCount: number, delayMultiplier: number) =>
new Promise((resolve) => setTimeout(resolve, delayMultiplier * retryCount));
export const exponentialBackOff = async <T>(
callback: () => Promise<T>,
options: { maxRetries: number; delayMultiplier: number } = {
maxRetries: 3,
delayMultiplier: 500,
},
retryCount = 0,
lastError?: unknown
): Promise<T> => {
if (retryCount > options.maxRetries) throw lastError;
try {
return callback();
} catch (e) {
await delay(retryCount, options.delayMultiplier);
return exponentialBackOff(callback, options, retryCount + 1, e);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment