SkillPilotAI

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.
JavaScript
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));
Output
API call: pAPI call: phAPI call: phoAPI call: phone

19.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.
JavaScript
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));
Output
API call: phone
Debounce timeline (300ms)
  1. 1.0ms "p" -> start timer

  2. 2.100ms "ph" -> clear old timer, start new

  3. 3.200ms "pho" -> clear, restart

  4. 4.300ms "phone" -> clear, restart

  5. 5.User stops; 600ms timer fires -> API call: phone

One call instead of four

19.3 Checkpoint: how many API calls?

JavaScript
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);
Output
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.
JavaScript
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);
Output
Scroll at 0Scroll at 300Scroll at 600Scroll at 900

19.5 Comparison: debounce vs throttle

PointDebounceThrottle
RunsOnce, after events stop for the delayAt most once per interval, during events
Gives youOnly the final valueRegular updates in between
Use casesSearch box, form validation, resize endScroll progress bar, mouse move, infinite scroll check
Built withClosure + clearTimeout/setTimeoutClosure + a flag + setTimeout
One-linerWaits for the user to stopKeeps 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).
JavaScript
// 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.
JavaScript
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));
Output
Paused on debugger, line 9Scope: total 1999Scope: item.price "199"
DevTools breakpoint flow
  1. 1.F12 -> Sources panel -> open your file

  2. 2.Click a line number to set a breakpoint (or write debugger)

  3. 3.Trigger the code; it pauses on that line

  4. 4.Check values in Scope, run expressions in Console

  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.
JavaScript
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);
Output
Polling: 100000Polling: 100000

19.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.