Skip to content

Instantly share code, notes, and snippets.

@antlis
Last active April 16, 2026 20:12
Show Gist options
  • Select an option

  • Save antlis/1cbf7224e1b1500740a7ed3ca86426e2 to your computer and use it in GitHub Desktop.

Select an option

Save antlis/1cbf7224e1b1500740a7ed3ca86426e2 to your computer and use it in GitHub Desktop.
Retries async operations with exponential backoff. Useful for flaky network requests or transient failures.
export async function retry(fn, {
retries = 3,
delay = 300,
factor = 2
} = {}) {
let attempt = 0;
while (true) {
try {
return await fn();
} catch (err) {
if (attempt >= retries) throw err;
const wait = delay * Math.pow(factor, attempt);
await new Promise(r => setTimeout(r, wait));
attempt++;
}
}
}
@antlis
Copy link
Copy Markdown
Author

antlis commented Apr 16, 2026

Use case:

await retry(() => fetch('/api').then(r => {
  if (!r.ok) throw new Error('fail');
  return r.json();
}));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment