CodePark/ problems / Retry with growing delays
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Async control flow

Retry with growing delays

mediumabout 25 minutes in an interview

Implement retryWithBackoff(fn, { retries, baseDelay }). fn takes no arguments and returns a promise.

  • Call fn right away. If it resolves, resolve with its value.
  • If it rejects, wait and try again, up to retries more times. So fn runs at most retries + 1 times.
  • The wait before retry number k is baseDelay * 2^(k - 1) ms, counting k from 1. With baseDelay = 100, the waits are 100, 200, 400, …
  • If every attempt fails, reject with the last error.
  • A synchronous throw from fn counts as a failed attempt. That means fn throws right away instead of returning a promise.
  • retries is 0 or more. With 0, there is one attempt and no waiting.
Input: retryWithBackoff(fetchUser, { retries: 3, baseDelay: 100 }) // fetchUser fails twice, then returns 'Ada' Output: attempts at 0, 100 and 300 ms; resolves 'Ada'
Input: retryWithBackoff(alwaysFails, { retries: 2, baseDelay: 50 }) Output: attempts at 0, 50 and 150 ms; rejects with the third error