Explorer
JavaScript

Write a function `debounce(fn, delay)` that returns a debounced version of fn. The function should only execute after delay ms have passed since the last call.

Problem Statement

<p>Write a function <code>debounce(fn, delay)</code> that returns a debounced version of fn. The function should only execute after delay ms have passed since the last call.</p>

Examples

Input: const debounced = debounce(fn, 200); debounced(); debounced();

Output: fn called once after 200ms of inactivity

Explanation: Timer resets on each consecutive trigger.

Complexity

Time Complexity: O(1)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: Debounce delays execution until the user stops triggering the function. šŸ’” Hint 2: Clear any existing timer on each call, then set a new timer. šŸ’” Hint 3: Use clearTimeout and setTimeout. Store the timer ID in a closure variable.

Editorial & Approach

Problem Overview & Intuition

To solve Debounce Function, we consider the execution characteristics of JavaScript engines. Write a function `debounce(fn, delay)` that returns a debounced version of fn. The function should only execute after delay ms have passed since the last call. 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 (debounce delays execution until the user stops triggering the function).
  3. Implement Logic: Handle state and transformations efficiently (clear any existing timer on each call, then set a new timer).
  4. Return Result: Ensure proper return format and preserve caller context if applicable.

Optimal Implementation (JavaScript)

function debounce(fn, delay) {
  let timer;
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

Complexity Analysis

Time Complexity O(1) wrapper invocation overhead
Space Complexity O(1) closure scope retention

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.

Debounce Function

Hard

Write a function debounce(fn, delay) that returns a debounced version of fn. The function should only execute after delay ms have passed since the last call.

Example Scenarios
1Example 1
Input: const debounced = debounce(fn, 200); debounced(); debounced();
Output: fn called once after 200ms of inactivity
Explanation:

Timer resets on each consecutive trigger.

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