Dev.to WebDev 🛠 Dev 👁 2 📖 2 min read

Debounce vs throttle in plain JavaScript: which one to use, with a test you can run

Both techniques stop a function from running too often, but they answer different questions. Debounce asks "has the user stopped?". Throttle asks "has enough time passed since the last run?". Picking the wrong one is a c

Both techniques stop a function from running too often, but they answer different questions. Debounce asks "has the user stopped?". Throttle asks "has enough time passed since the last run?". Picking the wrong one is a common source of laggy search boxes and janky scroll handlers.

Debounce: run once after things go quiet

Every new call resets a timer. The function only runs when no call arrives for wait milliseconds.

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

Good for: search-as-you-type, autosave, validating a field after the user pauses, resize handlers where only the final size matters.

Throttle: run at most once per interval

The first call runs right away. Calls during the cooldown are dropped.

function throttle(fn, wait) {
  let last = 0;
  return function (...args) {
    const now = Date.now();
    if (now - last >= wait) {
      last = now;
      fn.apply(this, args);
    }
  };
}

Good for: scroll position tracking, mouse-move handlers, anything that should keep updating while the user is still active.

Check the difference yourself

I ran this in Node. It fires 20 calls, 10 ms apart (about 200 ms total), against a 100 ms wait:

const calls = { d: 0, t: 0 };
const d = debounce(() => calls.d++, 100);
const t = throttle(() => calls.t++, 100);
let i = 0;
const iv = setInterval(() => {
  d(); t();
  if (++i === 20) {
    clearInterval(iv);
    setTimeout(() => console.log(calls), 200);
  }
}, 10);

Output on my run: { d: 1, t: 2 }. The debounced function ran once, after the calls stopped. The throttled one ran at the start and again around the 100 ms mark. Exact throttle counts can vary by a run or so with timer jitter, but debounce stays at 1 here.

Rule of thumb

  • Only the final value matters: debounce.
  • You want steady updates during activity: throttle.
  • Debounce can starve a function if calls never pause for wait ms. If that matters, use throttle or add a max-wait.

Browsers also have built-in options worth checking first: requestAnimationFrame for visual updates, and the input/change event choice for forms.

AI disclosure: I drafted this with AI assistance and ran the code above myself before posting.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.