Mid-level (2-5 years)JavaScript

What is the difference between debounce and throttle in JavaScript?

Quick answer

Debounce waits until the user stops triggering an event for a set time before running the function; throttle runs the function at most once per time interval no matter how often the event fires.

Use debounce when only the final value matters, such as a search box that should call the API after the user pauses typing. Use throttle when you want regular updates during continuous activity, such as scroll position tracking or window resize handling.

Both are built with closures and timers. In React, make sure the debounced function is created once (for example with useMemo or useRef), otherwise every render creates a new timer and the debounce does nothing.

function debounce(fn, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

function throttle(fn, limit) {
  let waiting = false;
  return (...args) => {
    if (waiting) return;
    fn(...args);
    waiting = true;
    setTimeout(() => { waiting = false; }, limit);
  };
}

Key points

  • Debounce: run after the burst ends
  • Throttle: run at a steady maximum rate
  • Both rely on closures to keep the timer between calls
  • What is prototypal inheritance in JavaScript?

    In JavaScript every object has an internal link to another object called its prototype, and property lookups walk up this prototype chain until the property is found or the chain ends.

  • How do you find and fix memory leaks in JavaScript?

    Take heap snapshots in Chrome DevTools before and after the suspect action, compare what grew, and fix the retaining reference, which is usually a forgotten listener, timer, global variable or unbounded cache.

  • What is the event loop in JavaScript and how does it work?

    The event loop is the mechanism that lets single-threaded JavaScript handle asynchronous work: it runs the call stack to empty, then runs all queued microtasks (promises), then takes the next task (timers, events) from the queue.

  • What is event delegation in JavaScript?

    Event delegation means attaching one listener to a parent element and using event bubbling to handle events from its children, instead of adding a listener to each child.