Exercise 14: Retry with Exponential Backoff
Problem Statement
Function `retryWithBackoff(fn, maxAttempts, baseDelay)` banao jo retry kare with exponential backoff.
Example: retryWithBackoff(fetchAPI, 3, 100) → delays: 100ms, 200ms, 400ms
Sample Output:
await retryWithBackoff(fetchAPI, 3, 100) // Retries with delays: 100ms, 200ms, 400ms
Solution
const retryWithBackoff = async (fn, maxAttempts = 3, baseDelay = 100) => {
let lastError;
for (let i = 0; i < maxAttempts; i++) {
try { return await fn(); }
catch (err) {
lastError = err;
if (i < maxAttempts - 1) await delay(baseDelay * Math.pow(2, i));
}
}
throw lastError;
};Explanation
Overall Goal:
- Retry with exponential backoff delays.
Real world:
- API retries: backoff strategy.
- Network calls: exponential delays.