Debounce, throttle and DevTools debugging
Events like typing and scrolling fire far more often than your code needs to react. Debounce and throttle, both built from a closure and setTimeout, control how often your function runs; DevTools breakpoints and cleanup of timers help you find bugs and avoid memory leaks.
19.1 The problem: an API call per key
- Typing "phone" fires an input event per key: 4 API calls for one word.
- More server load, and an older response can overwrite the newer one.
- Lift analogy: the door waits while people keep entering; each new person restarts the timer. That is debounce.
function search(q) { console.log("API call:", q);} // user types fast: a key every 100msconst keys = ["p", "ph", "pho", "phone"];keys.forEach((q, i) => setTimeout(() => search(q), i * 100));API call: pAPI call: phAPI call: phoAPI call: phone19.2 Write debounce yourself
- debounce(fn, ms) returns a new function (a closure) that remembers timer between calls.
- Every call clears the old timer and sets a new one.
- fn runs only when no call comes for ms milliseconds.
function debounce(fn, ms) { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), ms); };} const search = debounce((q) => { console.log("API call:", q);}, 300); const keys = ["p", "ph", "pho", "phone"];keys.forEach((q, i) => setTimeout(() => search(q), i * 100));API call: phone- Step 1
1.0ms "p" -> start timer
- Step 2
2.100ms "ph" -> clear old timer, start new
- Step 3
3.200ms "pho" -> clear, restart
- Step 4
4.300ms "phone" -> clear, restart
- Step 5
5.User stops; 600ms timer fires -> API call: phone
One call instead of four
19.3 Checkpoint: how many API calls?
import { debounce } from "./debounce.js"; const search = debounce((q) => { console.log("API call:", q);}, 300); setTimeout(() => search("re"), 0);setTimeout(() => search("red"), 200);setTimeout(() => search("redmi"), 600);API call: redAPI call: redmi- "red" at 200 cancelled "re"; red's timer completed at 500 and fired.
- "redmi" came at 600, after that call, so it gets its own call: 2 in total.
19.4 Throttle: at most once per fixed time
- A waiting flag: if true, the call is ignored.
- Otherwise fn runs immediately, waiting = true, and a timer resets it after ms.
- Scroll every 100ms with a 250ms throttle: 11 events, fn ran 4 times.
function throttle(fn, ms) { let waiting = false; return (...args) => { if (waiting) return; fn(...args); waiting = true; setTimeout(() => (waiting = false), ms); };} const onScroll = throttle((y) => { console.log("Scroll at", y);}, 250);for (let t = 0; t <= 1000; t += 100) setTimeout(() => onScroll(t), t);Scroll at 0Scroll at 300Scroll at 600Scroll at 90019.5 Comparison: debounce vs throttle
| Point | Debounce | Throttle |
|---|---|---|
| Runs | Once, after events stop for the delay | At most once per interval, during events |
| Gives you | Only the final value | Regular updates in between |
| Use cases | Search box, form validation, resize end | Scroll progress bar, mouse move, infinite scroll check |
| Built with | Closure + clearTimeout/setTimeout | Closure + a flag + setTimeout |
| One-liner | Waits for the user to stop | Keeps a fixed pace |
19.6 Common mistake: a new debounce per event
- Calling debounce inside the listener creates a new function with its own timer on every key: nothing is cancelled, 4 calls.
- Create the debounced function once, outside, and call it from the listener (same in React: create it once).
// Wrong: 4 API callsinput.addEventListener("input", (e) => { debounce(search, 300)(e.target.value);}); // Right: 1 API callconst debouncedSearch = debounce(search, 300);input.addEventListener("input", (e) => { debouncedSearch(e.target.value);});19.7 Find the bug with debugger and DevTools
- The cart total should be 2198 but shows a huge strange number.
- A debugger statement pauses the code on that line when DevTools is open.
- Scope shows item.price "199" is a string, so + concatenated instead of adding.
const cart = [ { name: "Shoes", price: 1999 }, { name: "Socks", price: "199" },]; function getTotal(items) { let total = 0; for (const item of items) { debugger; total = total + item.price; } return total;} console.log("Total:", getTotal(cart));Paused on debugger, line 9Scope: total 1999Scope: item.price "199"- Step 1
1.F12 -> Sources panel -> open your file
- Step 2
2.Click a line number to set a breakpoint (or write debugger)
- Step 3
3.Trigger the code; it pauses on that line
- Step 4
4.Check values in Scope, run expressions in Console
- Step 5
5.Step over (F10) line by line, Resume (F8) to continue
Also useful: conditional breakpoints and the Network tab
19.8 Memory leak: an interval that never stops
- The garbage collector frees only objects nothing references.
- The interval callback holds the msgs array via a closure; if it keeps running after the user leaves, the array stays forever.
- Return a cleanup function that calls clearInterval, and call it on leave.
function openChat() { const msgs = new Array(100_000).fill("hi"); const id = setInterval(() => { console.log("Polling:", msgs.length); }, 1000); return () => clearInterval(id);} const closeChat = openChat();// user leaves the chat after 2.5 secondssetTimeout(closeChat, 2500);Polling: 100000Polling: 10000019.9 Misconceptions and rules
- Debounce/throttle do not reduce browser events; the browser still fires every one, your function just runs less.
- No magic inside: just setTimeout and a closure, so be ready to write them in an interview.
- ~300ms is a common search delay; create the debounced function only once.
- Debug with breakpoints, conditional breakpoints and the Network tab, not only console.log.
- Every interval, timer or event listener needs cleanup, or you leak memory.
19.10 Interview tips
- Debounce: runs once after events stop for a delay (search box).
- Throttle: runs at most once per interval (scroll).
- Both are a closure + setTimeout; write them from memory.
- Create the debounced function once, not per event.
- Memory leaks come from references that stay alive: clear intervals and remove listeners.