⚡Flashcard Drill➔
NeetCode #958LC-2627MediumJavaScript
← Back to All Problems

#958 · #2627 · Debounce(防抖)

📌 Problem Statement & Constraints

Implement debounce(fn, t): return a wrapper that, after a burst of calls, invokes fn once only after t milliseconds of silence, using the arguments of the last call.

💡 Core Algorithmic Approaches

  1. On every call, clear the previous timer and set a fresh setTimeout.
  2. Only a silent period of t milliseconds lets the timer fire, so intermediate calls cancel each other.
  3. The arguments of the last call are used, because the timer callback closes over the latest args.
  4. Typical uses are search-box suggestions and window resize handlers.

💻 Benchmark Python3 Implementation

var debounce = function(fn, t) {
    let timer = null;
    return function(...args) {
        if (timer !== null) {
            clearTimeout(timer);              // cancel the pending call
        }
        timer = setTimeout(() => fn(...args), t);
    };
};

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(1): constant time per call.
💾 Space Complexity
O(1): one timer.

⚠️ Interview Pitfalls & Follow-ups

  • Forgetting clearTimeout: the wrapper then behaves like throttling or fires on every call, not like debounce.
  • Comparing timestamps manually: relying on setTimeout plus clearing is simpler and more reliable.
  • Confusing debounce with throttle: debounce fires after calls stop, throttle fires at a fixed interval.
  • Reading stale arguments in the timer callback: each call must capture its own args in a fresh closure.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related JavaScript Problems