MediumConcept

What is the difference between debounce and throttle in JavaScript?

Technology:
JavaScript
Experience:
Mid-level,
Senior

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.

Detailed explanation

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.

Example

javascript
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
  • JavaScriptMedium

    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.

    Junior · Mid-level · Browser & DOM
  • JavaScriptMedium

    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.

    Mid-level · Senior · Asynchronous Programming
  • HTMLMedium

    What is the difference between async and defer on script tags?

    Both download the script without blocking HTML parsing. defer waits until parsing finishes and runs scripts in document order; async runs a script as soon as it is downloaded, which can be before or after parsing and in any order.

    Mid-level · Senior · Browser & DOM
  • HTMLMedium

    How does the browser render a web page?

    The browser parses HTML into a DOM and CSS into a CSSOM, combines them into a render tree, computes layout (reflow), paints pixels and composites layers onto the screen.

    Mid-level · Senior · Browser & DOM
  • JavaScriptHard

    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.

    Senior · Memory Management