call(back)
FrontendmediumSign in to star problems

Retry With Exponential Backoff

Implement retry(task, options): call task(), which returns a promise, and if it rejects, wait and call it again, waiting longer each time.

retry(() => fetchJson(url), { retries: 3, delay: 100, factor: 2 });
// attempt at 0 ms; on failure wait 100, 200, then 400 ms between attempts
  • retries (default 3) is the number of extra attempts after the first; delay (default 100) is the first wait in ms; each later wait is the previous one times factor (default 2).
  • Resolve with the first fulfilment. After the last allowed attempt fails, reject with that error, without waiting again.
  • shouldRetry(error) (default: always) is consulted after each failure; when it returns false, reject with that error immediately.
  • Time spent inside task() is not part of the wait: the next wait starts when the failure arrives.

Everything runs on a virtual clock, so the grader sees exactly when each attempt starts and when the result settles.

Hints

Hint 1

An async function with a for loop reads best: try { return await task(); } catch (error) { ... }. The await inside try catches synchronous throws too.

Hint 2

Decide to stop before you wait: if this was the last allowed attempt, or shouldRetry says no, rethrow; otherwise await a timeout and multiply the wait.

Similar Problems6