Explorer
JavaScript

Write a function `retryWithBackoff(fn, maxRetries, baseDelay)` that retries an async function with exponential delays (baseDelay * 2^attempt).

Problem Statement

<p>Write a function <code>retryWithBackoff(fn, maxRetries, baseDelay)</code> that retries an async function with exponential delays (baseDelay * 2^attempt).</p>

Examples

Input: retryWithBackoff(fetchData, 3, 100)

Output: Data on success, or throws error after 3 retries

Explanation: Retries with delays of 100ms, 200ms, 400ms.

Complexity

Time Complexity: O(N)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: On each retry, the delay doubles: baseDelay, baseDelay*2, baseDelay*4, etc. šŸ’” Hint 2: Use a loop or recursion with await for the delay. šŸ’” Hint 3: On failure, wait baseDelay * Math.pow(2, attempt) ms before retrying.

Editorial & Approach

Problem Overview & Intuition

To solve Retry with Exponential Backoff, we consider the execution characteristics of JavaScript engines. Write a function `retryWithBackoff(fn, maxRetries, baseDelay)` that retries an async function with exponential delays (baseDelay * 2^attempt). By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.

Step-by-Step Approach

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (on each retry, the delay doubles: basedelay, basedelay*2, basedelay*4, etc).
  3. Implement Logic: Handle state and transformations efficiently (use a loop or recursion with await for the delay).
  4. Return Result: Ensure proper return format and preserve caller context if applicable.

Optimal Implementation (JavaScript)

async function retryWithBackoff(fn, maxRetries, baseDelay) {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (err) {
      if (attempt === maxRetries) throw err;
      await new Promise(r => setTimeout(r, baseDelay * Math.pow(2, attempt)));
    }
  }
}

Complexity Analysis

Time Complexity O(N) linear scan over input
Space Complexity O(1) constant auxiliary space (or O(N) output)

Edge Cases & Corner Traps Handled

  • Empty or boundary inputs (empty arrays, strings, zero length).
  • Type checks and unexpected values (e.g. null, undefined, negative numbers).
  • Closure preservation and memory isolation between separate invocations.

Retry with Exponential Backoff

Hard

Write a function retryWithBackoff(fn, maxRetries, baseDelay) that retries an async function with exponential delays (baseDelay * 2^attempt).

Example Scenarios
1Example 1
Input: retryWithBackoff(fetchData, 3, 100)
Output: Data on success, or throws error after 3 retries
Explanation:

Retries with delays of 100ms, 200ms, 400ms.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
done