Retry With Backoff in JavaScript

Level 5439 keystrokes

Retry with exponential backoff handles transient failures by increasing delays between retries.

JavaScript code

// Async function that retries with exponential backoff
1async function retryWithBackoff(fn, retries = 3, delay = 100) {
// Try up to 'retries' times
2 for (let i = 0; i < retries; i++) {
3 try {
// await inside try, so a rejection is caught below
4 return await fn();
5 } catch (e) {
// If last retry, throw the error
6 if (i === retries - 1) throw e;
// Log retry attempt
7 console.log(`Retry ${i + 1} after ${delay}ms`);
// Wait before retrying
8 await new Promise(r => setTimeout(r, delay));
// Double the delay for next retry (exponential backoff)
9 delay *= 2;
10 }
11 }
12}
13
// Simulate a flaky function that fails twice then succeeds
14let attempts = 0;
15const flakyFn = () => ++attempts < 3 ? Promise.reject("fail") : Promise.resolve("success");
16
// Test: should retry and eventually succeed
17retryWithBackoff(flakyFn).then(console.log);

Output

Retry 1 after 100ms
Retry 2 after 200ms
success
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • (× 13
  • )× 13
  • =× 11
  • ;× 10
  • {× 6
  • }× 6
  • .× 5
  • +× 5
  • "× 4
  • ,× 3

More JavaScript examples at level 5

← JavaScript typing practice