Skip to content

CodeNot attempted

Retry with exponential backoff + abort

Difficulty: hard

Call fn(signal). If it rejects, wait and try again, up to retries extra times (at most retries + 1 calls).

  • wait before retry n (0-based) = baseDelayMs * 2 ** n plus random jitter of 0..baseDelayMs
  • resolve with the first success; after the last failure reject with that attempt's error
  • opts.signal: if it aborts (before or during a wait), stop immediately, clear the timer and reject with signal.reason
  • pass a signal to fn so it can cancel its own work too
Show reference solution
// Waits `ms`, but stops early with the abort reason if the signal is aborted.
function wait(ms: number, signal: AbortSignal): Promise<void> {
return new Promise((resolve, reject) => {
const timer = setTimeout(resolve, ms);
signal.addEventListener(
'abort',
() => {
clearTimeout(timer);
reject(signal.reason);
},
{ once: true },
);
});
}
export async function retry<T>(
fn: (signal: AbortSignal) => Promise<T>,
opts: { retries: number; baseDelayMs: number; signal?: AbortSignal },
): Promise<T> {
const signal = opts.signal ?? new AbortController().signal;
let attempt = 0;
while (true) {
if (signal.aborted) {
throw signal.reason;
}
try {
return await fn(signal);
} catch (error) {
if (attempt === opts.retries) {
throw error; // no retries left: give up with the last error
}
await wait(opts.baseDelayMs * 2 ** attempt, signal); // 1x, 2x, 4x, ...
attempt++;
}
}
}
Loading editor…