Retry with Exponential Backoff
MediumP2Coding
Implement retry(fn, retries, baseDelay) for an async function fn that may fail.
It calls fn() and returns a promise that:
- resolves with the result of the first call that succeeds,
- after a failed call, waits and calls
fnagain, up toretriesextra times (sofnruns at mostretries + 1times), - waits
baseDelay * 2^kmilliseconds before retry numberk + 1(exponential backoff:baseDelay, then2 * baseDelay, then4 * baseDelay, ...), - if every attempt fails, rejects with the error from the last attempt.
There is no delay before the first call and none after the last failure. retries may be 0.
Example 1
- Input
- retry(flaky, 3, 100)
- Output
- calls flaky, waits 100 ms, 200 ms, 400 ms between failures, resolves on the first success
Constraints
- 0 <= retries <= 10
- 0 <= baseDelay <= 1000
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 8. ⌘Enter runs, ⌘⇧Enter submits.