Home
← All questions

Keep trying a flaky operation with growing pauses in JavaScript

MediumPremiumJavaScript

Asked at Uber · Razorpay

JavaScript interview practice: When an async operation fails, wait, try again, and double the wait each time — stop after a fixed number of extra attempts.

Problem

Network calls fail for brief moments — a timeout, a blip, a temporary overload. Instead of failing on the first error, build a helper that calls the operation again after a pause, and makes each pause longer than the last so you do not hammer a struggling server.

Implement retry(fn, retries, delay) where:

  • fn is a function returning a promise (the operation to attempt).
  • On rejection, wait delay ms and try again, doubling the delay each time.
  • Give up after retries additional 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 extra attempts).

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
}
Premium question

Unlock the in-browser editor, test cases, and model solution with Mentoxis Premium.

Unlock with Premium