Problem
Network calls fail transiently — a request times out, a server hiccups, a rate limit trips. Instead of failing instantly, resilient clients retry a few times with increasing delays (exponential backoff) so they don't stampede a struggling server.
Implement retry(fn, retries, delay) where:
fnis a function returning a promise (the operation to attempt).- On rejection, wait
delayms and try again, doubling the delay each time (backoff). - Give up after
retriesadditional attempts and reject with the last error. - Resolve as soon as any attempt succeeds.
Note: the total number of calls is retries + 1 (the initial try plus the retries).
Input
let tries = 0;
const flaky = () =>
new Promise((res, rej) => (++tries < 3 ? rej("fail " + tries) : res("ok")));
retry(flaky, 5, 100).then(console.log); // succeeds on the 3rd attempt
Expected output
- Resolves with
"ok"after 3 attempts.
Implement from scratch:
function retry(fn, retries = 3, delay = 500) {
// Your code here
}