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 backoff1async function retryWithBackoff(fn, retries = 3, delay = 100) { // Try up to 'retries' times2 for (let i = 0; i < retries; i++) {3 try { // await inside try, so a rejection is caught below4 return await fn();5 } catch (e) { // If last retry, throw the error6 if (i === retries - 1) throw e; // Log retry attempt7 console.log(`Retry ${i + 1} after ${delay}ms`); // Wait before retrying8 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 succeeds14let attempts = 0;15const flakyFn = () => ++attempts < 3 ? Promise.reject("fail") : Promise.resolve("success");16 // Test: should retry and eventually succeed17retryWithBackoff(flakyFn).then(console.log);Output
Retry 1 after 100ms Retry 2 after 200ms success
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