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
- On every call, clear the previous timer and set a fresh
setTimeout. - Only a silent period of
tmilliseconds lets the timer fire, so intermediate calls cancel each other. - The arguments of the last call are used, because the timer callback closes over the latest
args. - 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
setTimeoutplus 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
argsin 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.