JavaScript Advanced Browser APIs · 9 min read

Debounce and Throttle Event Handlers

Lesson 17 of 38 in the JavaScript learning path.

How do I stop a search input or scroll handler from running too often?

Input and scroll events can fire dozens of times a second. A search that filters or fetches on every keystroke does more work than the student can see, and a scroll handler that writes the DOM on every pixel can drop frames. Debounce waits until the events pause. Each new call clears the previous timer and starts another, so the function runs once after the quiet period. Throttle lets a call through, then ignores further calls until a gap has passed, with one trailing call for the last event in the burst.

The search box uses a 300 millisecond debounce. The scroll box counts every scroll immediately and counts a throttled run about once per 200 milliseconds. Both wrappers keep the timer id and expose cancel, which clears it. Rest collects the arguments so the wrapped function still receives the query string. Clearing the timer on reset stops a search that the student already abandoned.

Syntax & Parameters

Syntax
const debounced = debounce(fn, 300);
const throttled = throttle(fn, 200);
debounced.cancel();
throttled.cancel();

Example

Interactive preview available
app.js
'use strict';

function debounce(fn, waitMs) {
  let timerId = 0;
  const wrapped = (...args) => {
    window.clearTimeout(timerId);
    timerId = window.setTimeout(() => { timerId = 0; fn(...args); }, waitMs);
  };
  wrapped.cancel = () => { window.clearTimeout(timerId); timerId = 0; };
  return wrapped;
}

function throttle(fn, waitMs) {
  let lastRun = 0;
  let timerId = 0;
  const wrapped = (...args) => {
    const remaining = waitMs - (Date.now() - lastRun);
    if (remaining <= 0) {
      window.clearTimeout(timerId);
      timerId = 0;
      lastRun = Date.now();
      fn(...args);
      return;
    }
    if (timerId !== 0) return;
    timerId = window.setTimeout(() => { lastRun = Date.now(); timerId = 0; fn(...args); }, remaining);
  };
  wrapped.cancel = () => { window.clearTimeout(timerId); timerId = 0; };
  return wrapped;
}

const lessons = ['Scope', 'Destructuring', 'Arrays', 'Selectors', 'Forms', 'Fetch', 'Modules'];
const search = document.getElementById('lesson-search');
const results = document.getElementById('search-results');
const scrollBox = document.getElementById('scroll-box');
const scrollStat = document.getElementById('scroll-stat');
const rawStat = document.getElementById('raw-stat');
let rawScrolls = 0;
let throttledScrolls = 0;

function renderMatches(query) {
  const needle = String(query).trim().toLowerCase();
  const matched = lessons.filter((title) => title.toLowerCase().includes(needle));
  const text = matched.length === 0 ? 'No lessons' : matched.join('\n');
  if (results !== null) results.textContent = text;
  console.log(text);
}

const runSearch = debounce((value) => renderMatches(value), 300);
const countScroll = throttle(() => {
  throttledScrolls += 1;
  if (scrollStat !== null) scrollStat.textContent = String(throttledScrolls);
}, 200);

if (search instanceof HTMLInputElement) search.addEventListener('input', () => runSearch(search.value));
if (scrollBox !== null) {
  scrollBox.addEventListener('scroll', () => {
    rawScrolls += 1;
    if (rawStat !== null) rawStat.textContent = String(rawScrolls);
    countScroll();
  });
}
const reset = document.getElementById('reset-handlers');
if (reset !== null) reset.addEventListener('click', () => { runSearch.cancel(); countScroll.cancel(); });
renderMatches('');

Expected Output

On load, #search-results:
Scope
Destructuring
Arrays
Selectors
Forms
Fetch
Modules

After the input pauses on fe:
Fetch

Raw scroll events increment #raw-stat once each. #scroll-stat increments on the first event and then at most once per 200 milliseconds. Reset clears a pending search timer and a pending trailing scroll timer.

Line-by-Line Walkthrough

  1. debounce keeps one timer id. Each call clears that timer and starts a new one, so only the last pause runs the function.
  2. The timer callback clears the id, then calls the original function with the rest arguments that were saved for that call.
  3. cancel clears the same timer and zeroes the id, which drops a search that should not run after a reset.
  4. throttle records the last run time. When the wait has already elapsed, it runs immediately and clears any trailing timer.
  5. When the wait has not elapsed and no trailing timer exists, throttle schedules one call for the remaining time.
  6. Further events inside that window return early, so a burst becomes one leading run plus at most one trailing run.
  7. The lesson list is local. renderMatches trims the query, filters titles, and writes the matches with textContent.
  8. The input listener does not filter immediately. It hands the current value to the debounced wrapper, which waits 300 milliseconds.
  9. The scroll listener increments the raw counter on every event and calls the throttled counter, which updates about every 200 milliseconds.
  10. Reset cancels both timers. The initial renderMatches call lists every lesson before the student types.

Common Pitfalls & Security

Debounce and throttle feel similar and solve different problems. Debounce on a scroll counter never runs while the student is still scrolling. Throttle on a search box fires in the middle of a word. Both need a stored timer id. If you forget clearTimeout, a stale callback can filter with an old query or increment the counter after the widget is gone. A trailing throttle also closes over the latest arguments only if you keep them. The version here passes the arguments from the scheduled call.

  • A debounce of 0 still waits a macrotask. It is not the same as calling the function now.
  • Losing the timer id makes cancel impossible. Keep it in the closure and clear it before you set the next one.
  • Throttle that only runs on the leading edge drops the final scroll position. Keep the trailing call when the last event matters.
  • Do not point the debounced search at an untrusted HTML builder. results.innerHTML = query with the untrusted string <img src="x" alt="untrusted"> is an XSS hole. Use textContent.
  • A fetch inside the debounced function still needs a timeout and a check of response.ok. Debounce reduces calls. It does not fix error handling.

Best Practices & Modern Standards

Debounce text input that starts a search or a save. Throttle scroll, resize, and pointer movement that update a counter or a position. Pick the wait from the interaction: a few hundred milliseconds for typing, and a shorter gap for scroll. Always clear the timer in cancel, and call cancel when the widget is reset or removed. ES2024 does not ship a built-in debounce. Write the small wrapper, or use one you can read, and keep the timer local to it.

Pass arguments with rest and spread so the wrapper does not hard-code a single parameter. Render matches as text. If the debounced work becomes a network call, ignore stale responses or abort the previous request so a slow answer cannot overwrite a newer query.

Real-World Use

A course catalog has a search box above hundreds of lesson titles. Filtering on every keystroke is wasted work, and a fetch on every keystroke is worse. Debounce waits until the student pauses, then filters the local list or sends one request. The reset control cancels the timer so a cleared box does not flash an old query.

A progress sidebar on the same page listens to scroll inside the lesson and updates a "still reading" counter. Throttle keeps that counter honest without rewriting the DOM on every pixel. The raw count and the throttled count sit side by side so the student can see how many events were collapsed.

Frequently Asked Questions

When do I debounce instead of throttle?

Debounce fits work that should run after the events stop, such as a search box. Throttle fits work that should keep sampling while the events continue, such as a scroll counter. Using the wrong one either waits forever or fires too early.

Why clear the previous timeout?

Without clearTimeout, every keystroke schedules another run. The function then fires once per keystroke after the delay, which is the pile-up you were trying to avoid. Clear the old id before you store the new one.

What does cancel need to do?

It should clear the pending timeout and reset the id so a later schedule is not confused with a live one. Call it when the student resets the search or when the widget is removed from the page.

Does throttle drop the last event?

A leading-only throttle can. This wrapper schedules one trailing call when events arrive during the wait, so the last burst still produces a run. Further events in that window do not schedule a second trailing call.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…