Back to More
Concept in 60s

Debouncing vs Throttling

One concept. 60 seconds. No fluff.

What Are They?

Both are techniques to control how often a function runs. Both are used for performance optimization. But they solve different problems.

Debouncing β€” Wait until the user stops doing something, then run the function.

Throttling β€” Run the function at most once every N milliseconds, no matter how often it is triggered.

πŸ”„ Debouncing Explained

Imagine a search bar that fetches results as you type. Without debouncing, it fires an API call on every keystroke. With debouncing, it waits until you stop typing β€” then fires once.

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

const search = debounce(async (query) => {
  const res = await fetch(`/api/search?q=${query}`);
  // update UI
}, 300);

Use debouncing for: search inputs, form autosave, window resize handlers.

⏱️ Throttling Explained

Imagine tracking scroll position. Without throttling, the event fires hundreds of times per second. With throttling, it fires at most once every 100ms β€” smooth and performant.

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

const handleScroll = throttle(() => {
  console.log("Scrolled!", window.scrollY);
}, 100);

Use throttling for: scroll events, resize events, mousemove, game loops.

When to Use What

ScenarioUse
Search input that calls an APIDebounce
Save button that sends a requestDebounce
Scrolling to load more contentThrottle
Resize event to recalculate layoutThrottle
Button to prevent double-clickDebounce

TL;DR

Debounce β€” β€œWait until you are done.”

Throttle β€” β€œAt most once per interval.”

In production, use Lodash's _.debounce() and _.throttle() β€” they handle edge cases.