⚡ Fix a Debounced Function Still Firing Once per Call Instead of Once per Burst Because the Timer Variable Is Declared Inside the Returned Function Instead of the Outer Closure
A correct debounce implementation relies on one shared timer identifier that persists across every call to the debounced function, so each new call can cancel the pending timeout left over from the previous one before scheduling its own. That sharing only works if the timer variable lives in the outer factory function’s closure, declared once when the debounced function is created. Declaring let timer inside the function that actually gets called and returned, instead of in the function that creates and returns it, means a brand new, independent timer variable is created fresh on every single call — clearTimeout(timer) at the top of the function has nothing from a previous call to actually cancel, because that previous call’s timer variable already went out of scope the moment it returned.
🔎 The Problem
// Bug: timer declared inside the returned function
function debounce(fn, delay) {
return function (...args) {
let timer; // <- new variable every single call
clearTimeout(timer); // <- always clearing a timer that was
// just created undefined; never the
// previous call's actual timer
timer = setTimeout(() => fn(...args), delay);
};
}
// Result: every call schedules its own independent timeout.
// Calling it 5 times in a row fires fn 5 times, each `delay` after
// its own call - not once, `delay` after the last call.
✅ The Fix
- Move the timer variable’s declaration up into the outer function — the one that runs once and returns the debounced function — so the same variable is captured by the closure and shared across every call instead of being recreated each time.
- Add a quick manual test: call the debounced function several times in rapid succession and count how many times the wrapped function actually runs — a correct debounce runs it exactly once, well after the last call, not once per call.
- If you reach for a utility library’s debounce instead of writing your own, you get this closure handled correctly for free — worth it specifically because this exact bug is easy to introduce and easy to miss in a quick glance at otherwise-reasonable-looking code.
🚨 Why This Is Dangerous
- A debounce that silently degrades into firing on every call still looks like it’s working in a slow, deliberate manual test with single, well-spaced clicks — it only reveals itself under the rapid, bursty input (fast typing, a dragged slider) that debouncing was supposed to be protecting against in the first place.
A debounce is only as shared as its timer variable — put that variable in the wrong scope and every call gets its own private, useless copy of the thing that was supposed to be shared.
