Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 37 ยท JavaScript Performance

Debounce, Throttle and Idle Work

Stop scroll, resize and input events from flooding the main thread. Learn debounce, throttle, passive listeners, requestAnimationFrame and idle callbacks.

Some events fire far more often than you need. A scroll can fire 60 times a second, mousemove even more, and a user typing "performance" fires input eleven times in a second. If each event triggers a heavy handler, the main thread drowns.

The fix is to run the handler less often. Two classic tools do that, debounce and throttle, and the browser adds three more: requestAnimationFrame, passive listeners and idle callbacks.

Debounce: wait until things settle

A debounced function runs only after events have stopped for a given time. It is perfect for search-as-you-type, validation and saving a draft: you only care about the final state.

flowchart LR
  K["Keystrokes: p e r f"] --> W["Timer resets on each key"]
  W --> Q["300 ms of silence"] --> R["Run search once"]

Every new event cancels the pending call and starts the timer again.

JS A debounce function

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Choose the wait carefully: 150 to 300 ms feels natural for search boxes. A leading-edge debounce (run on the first event, ignore the rest) suits buttons where you want an immediate reaction and no double submit.

Throttle: at most once per interval

A throttled function runs at most once every N milliseconds while events continue. Use it when you need regular updates during the activity: scroll position indicators, drag handling, resize measurements.

JS A throttle function

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Debounce Throttle
Runs once, after a pause regularly, during activity
Best for search input, form validation, autosave scroll, resize, drag, pointer move
Risk delay if events never stop may miss the final value (add a trailing call)

requestAnimationFrame: sync with the screen

If your handler changes visuals, doing it more than once per frame is wasted. requestAnimationFrame (rAF) runs your callback right before the next paint, so you update at most once per frame:

JavaScript
let ticking = false;
window.addEventListener("scroll", () => {
  if (ticking) return;
  ticking = true;
  requestAnimationFrame(() => {
    progressBar.style.transform = `scaleX(${scrollY / maxScroll})`;
    ticking = false;
  });
}, { passive: true });

This is the preferred "throttle" for anything visual: it adapts to the display's refresh rate and pauses in background tabs.

Passive listeners

Touch and wheel listeners can call preventDefault() to cancel scrolling. Because the browser cannot know whether you will, it used to wait for your handler before scrolling, which caused jank. Declare { passive: true } to promise you will not cancel:

JavaScript
document.addEventListener("touchstart", onTouch, { passive: true });

Chrome treats touch and wheel listeners on the window, document and body as passive by default, but being explicit documents your intent and works everywhere. Use { passive: false } only when you really call preventDefault().

Event delegation

Instead of attaching a listener to each of 1,000 list items, attach one to the parent and inspect event.target. That saves memory and setup time, and it works for items added later.

JavaScript
list.addEventListener("click", (event) => {
  const item = event.target.closest("li[data-id]");
  if (item) selectItem(item.dataset.id);
});

Idle work

Not everything has to happen now. Analytics batching, prefetching, cache warming and index building can wait for a quiet moment. requestIdleCallback runs a function when the browser has spare time and tells you how much:

JavaScript
function whenIdle(task) {
  if ("requestIdleCallback" in window) {
    requestIdleCallback((deadline) => {
      if (deadline.timeRemaining() > 5) task();
      else whenIdle(task);
    }, { timeout: 2000 });
  } else {
    setTimeout(task, 200); // Safari fallback
  }
}

whenIdle(() => sendAnalyticsBatch());

The timeout option guarantees the task eventually runs even on a busy page. Never touch the DOM heavily inside an idle callback; keep it for background bookkeeping.

Choosing the right tool

  1. Visual update on scroll or pointer move: requestAnimationFrame.
  2. Repeated work during continuous events: throttle.
  3. Reaction to the final value: debounce.
  4. Non-urgent bookkeeping: idle callback.
  5. Many similar elements: event delegation.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A search box should query the server only after the user pauses typing. Which tool fits?

    Debounce waits for a quiet period and then runs once with the latest value.
  2. 2. You want a scroll progress bar updated smoothly. What is the best approach?

    rAF ties updates to the screen refresh, so you never do more visual work than the user can see.
  3. 3. What does { passive: true } promise the browser?

    Passive listeners let the browser scroll without waiting for the handler.
  4. 4. What is the purpose of the timeout option of requestIdleCallback?

    Without a timeout, a continuously busy page might never become idle.

Summary

  • Frequent events need rate limiting: debounce for the final value, throttle for steady updates.
  • Use requestAnimationFrame for visual updates and passive listeners for touch and wheel.
  • Delegate events from a parent when there are many similar children.
  • Move non-urgent work to idle time with a timeout and a fallback.

Next: Web Workers: Moving Work Off the Main Thread