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
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
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
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (debounce delays execution until the user stops triggering the function).
- Implement Logic: Handle state and transformations efficiently (clear any existing timer on each call, then set a new timer).
- 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
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.