Skip to content

Instantly share code, notes, and snippets.

@Yuripetusko
Last active November 15, 2024 13:42
Show Gist options
  • Select an option

  • Save Yuripetusko/cb7d7f176115e09738c7f728aa25191d to your computer and use it in GitHub Desktop.

Select an option

Save Yuripetusko/cb7d7f176115e09738c7f728aa25191d to your computer and use it in GitHub Desktop.
export function retryWithExponentialBackoff<T extends () => Promise<Awaited<ReturnType<T>>>>(
fn: T,
maxAttempts = 5,
baseDelayMs = 1000,
) {
let attempt = 1;
const execute = async () => {
try {
return await fn();
} catch (error) {
if (attempt >= maxAttempts) {
throw error;
}
const delayMs = baseDelayMs * 2 ** attempt;
console.log(`Retry attempt ${attempt} after ${delayMs}ms`);
await new Promise((resolve) => setTimeout(resolve, delayMs));
attempt++;
return execute();
}
};
return execute();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment