Debounce vs throttle is one of the first performance questions in front-end work, because browsers fire some events far more often than your code needs. Typing fires input on every key, scrolling fires dozens of scroll events per second, and resizing a window fires resize continuously. Both techniques limit how often a function runs, but they answer different questions. Debounce waits until the events stop and then runs once. Throttle runs at a steady rate while the events continue. This guide shows the difference on a measured timeline, gives dependency-free implementations with cancel and flush, adds a frame-synced variant with requestAnimationFrame, builds a search box that also cancels stale requests, and tests all of it with Node.js mock timers. Every snippet was run on Node.js 26; the browser examples were exercised with small DOM stubs.

Debounce vs throttle timeline: a burst of 20 events produces one debounced call after the pause and a throttled call every 200 milliseconds
Debounce runs once after a burst of events ends; throttle runs at a fixed rate while the burst continues.

From my own work: On sites I audit, the most common version of this problem is a search box that sends one API request per keystroke, often with responses arriving out of order so the results flicker. Debouncing the input and aborting the previous request fixes both the server load and the flicker in about twenty lines.

Debounce vs throttle on a real timeline

This script fires an event every 50 ms for one second, 20 events in total, and passes each one to a debounced and a throttled function with a 200 ms wait:

// demo.mjs - fire an event every 50 ms for 1 second and count the calls
import { debounce, throttle } from "./timing.js";

const start = Date.now();
const t = () => String(Date.now() - start).padStart(4) + " ms";
const counts = { raw: 0, debounced: 0, throttled: 0 };

const onDebounced = debounce((i) => { counts.debounced++; console.log(`${t()}  debounced  event #${i}`); }, 200);
const onThrottled = throttle((i) => { counts.throttled++; console.log(`${t()}  throttled  event #${i}`); }, 200);

let i = 0;
const source = setInterval(() => {
  i++;
  counts.raw++;
  onDebounced(i);
  onThrottled(i);
  if (i === 20) clearInterval(source);
}, 50);

setTimeout(() => console.log(counts), 1500);
$ node demo.mjs
  51 ms  throttled  event #1
 251 ms  throttled  event #4
 453 ms  throttled  event #8
 654 ms  throttled  event #12
 856 ms  throttled  event #16
1057 ms  throttled  event #20
1221 ms  debounced  event #20
{ raw: 20, debounced: 1, throttled: 6 }

The throttled function ran immediately on the first event and then every 200 ms, six times, always with the latest event. The debounced function ran exactly once, 200 ms after the last event, with the final value. That is the whole difference, and it matches the definitions on MDN for debounce and throttle.

Situation Use Why
Search or autocomplete input Debounce, 250 to 400 ms Only the final query matters
Autosave a draft Debounce, 1 to 2 s, plus flush on leave Save after the user pauses
Form field validation Debounce, 300 to 500 ms Do not show errors while the user is typing
Recalculate layout after resize Debounce, 100 to 200 ms Intermediate sizes are thrown away
Sticky header, scroll progress bar, parallax requestAnimationFrame throttle Update once per frame, never more
Infinite scroll or lazy loading checks Throttle, 100 to 250 ms, or IntersectionObserver Needs regular checks during scrolling
Drag, mouse move, pointer tracking sent to a server Throttle Steady updates, bounded rate
Button double-clicks on submit Leading debounce, or disable the button Act on the first click, ignore the rest

A useful rule of thumb: if the user would be satisfied seeing only the final state, debounce. If they need feedback while the action is still happening, throttle.

A debounce implementation with leading, cancel and flush

Each call clears the previous timer and starts a new one, so the function only runs when the calls stop for wait milliseconds. The leading option runs on the first call of a burst instead of the last, which is what you want for buttons:

// timing.js - debounce and throttle with cancel/flush, no dependencies

export function debounce(fn, wait = 300, { leading = false } = {}) {
  let timer = null;
  let lastArgs;
  let lastThis;

  function debounced(...args) {
    lastArgs = args;
    lastThis = this;
    const callNow = leading && timer === null;
    clearTimeout(timer);
    timer = setTimeout(() => {
      timer = null;
      if (!leading) fn.apply(lastThis, lastArgs);
    }, wait);
    if (callNow) fn.apply(lastThis, lastArgs);
  }

  debounced.cancel = () => {
    clearTimeout(timer);
    timer = null;
  };

  // run a pending trailing call immediately, e.g. before the page unloads
  debounced.flush = () => {
    if (timer === null) return;
    clearTimeout(timer);
    timer = null;
    if (!leading) fn.apply(lastThis, lastArgs);
  };

  return debounced;
}
  • It keeps this and the latest arguments, so it works for object methods and event handlers. Use a regular function, not an arrow function, for the wrapper, or this is lost.
  • cancel() drops a pending call. Call it when a component unmounts or a dialog closes, so a stale callback does not run against removed elements.
  • flush() runs a pending call now. Use it when the user presses Enter in a search box or leaves the page with an unsaved draft.

A throttle implementation with leading and trailing calls

A throttle that only uses the leading edge loses the last event of a burst, so a scroll-position indicator stops a few pixels short or the final drag position is never sent. This version runs immediately when enough time has passed and otherwise schedules one trailing call with the most recent arguments:

export function throttle(fn, wait = 200) {
  let last = 0;          // time of the last call to fn
  let timer = null;
  let lastArgs;
  let lastThis;

  function throttled(...args) {
    const now = Date.now();
    const remaining = wait - (now - last);
    lastArgs = args;
    lastThis = this;
    if (remaining <= 0) {
      // leading edge: enough time has passed, call right away
      clearTimeout(timer);
      timer = null;
      last = now;
      fn.apply(lastThis, lastArgs);
    } else if (timer === null) {
      // trailing edge: schedule one call with the latest arguments
      timer = setTimeout(() => {
        last = Date.now();
        timer = null;
        fn.apply(lastThis, lastArgs);
      }, remaining);
    }
  }

  throttled.cancel = () => {
    clearTimeout(timer);
    timer = null;
    last = 0;
  };

  return throttled;
}

Lodash’s _.throttle follows the same leading-and-trailing default, and its _.debounce adds a maxWait option that forces a call during non-stop input (Lodash documentation). If you already ship Lodash, its versions are well tested; importing only the functions you need, such as lodash-es/debounce, keeps the bundle small. Writing your own is about 60 lines and removes a dependency.

Throttle to the frame rate with requestAnimationFrame

For anything that changes what is on screen, a fixed millisecond interval is the wrong unit. The browser paints once per frame, about every 16.7 ms on a 60 Hz display and more often on faster screens. requestAnimationFrame schedules a callback right before the next paint (MDN: requestAnimationFrame), so a frame-based throttle does the work exactly once per frame, no matter how many events arrived:

// one call per animation frame, for work that updates the screen
export function rafThrottle(fn) {
  let frame = null;
  let lastArgs;
  return function (...args) {
    lastArgs = args;
    if (frame !== null) return;
    frame = requestAnimationFrame(() => {
      frame = null;
      fn.apply(this, lastArgs);
    });
  };
}
// scroll.js - visual updates once per frame, layout work after resizing stops
import { debounce, rafThrottle } from "./timing.js";

const header = document.querySelector("header");

window.addEventListener("scroll", rafThrottle(() => {
  header.classList.toggle("is-compact", window.scrollY > 80);
}), { passive: true });

window.addEventListener("resize", debounce(() => {
  document.documentElement.style.setProperty("--vh", `${window.innerHeight * 0.01}px`);
}, 150));

In a test with 50 scroll events dispatched in one burst, the header toggle ran once. The { passive: true } option tells the browser the listener will never call preventDefault(), so scrolling can start without waiting for your JavaScript (MDN: passive listeners). Combined with frame throttling, this keeps scroll handlers from hurting responsiveness; long tasks in event handlers show up directly in Interaction to Next Paint, as explained in the Core Web Vitals guide.

Before reaching for a scroll handler at all, check whether the browser has a dedicated API. IntersectionObserver handles lazy loading, infinite scroll and is this element visible checks without any scroll events, and ResizeObserver reports element size changes. CSS position: sticky replaces many sticky-header scripts entirely.

Debouncing reduces the number of requests, but it does not stop an older, slower response from arriving after a newer one and overwriting the results. The fix is to abort the previous request whenever a new search starts:

// search.js - search as you type: debounce the input, abort stale requests
import { debounce } from "./timing.js";

const input = document.querySelector("#search");
const list = document.querySelector("#results");
let controller = null;

async function search(query) {
  controller?.abort();                       // cancel the previous request
  if (query.length < 2) {
    list.textContent = "";
    return;
  }
  controller = new AbortController();
  try {
    const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
      signal: AbortSignal.any([controller.signal, AbortSignal.timeout(5000)]),
    });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const items = await res.json();
    list.replaceChildren(...items.map((item) => {
      const li = document.createElement("li");
      li.textContent = item.title;
      return li;
    }));
  } catch (err) {
    if (err.name === "AbortError") return;   // replaced by a newer query: ignore
    list.textContent = err.name === "TimeoutError" ? "Search is slow, try again." : "Search failed.";
  }
}

const debouncedSearch = debounce(search, 300);
input.addEventListener("input", (e) => debouncedSearch(e.target.value.trim()));
// Enter should not wait for the pause
input.addEventListener("keydown", (e) => { if (e.key === "Enter") debouncedSearch.flush(); });

Typing debounce one letter every 50 ms sent exactly one request, for the full word. When a new query started while an older request was still running, the older request was aborted and its AbortError was ignored, so only the newest results were shown. The 5 second timeout through AbortSignal.timeout() and the way AbortSignal.any() combines it with the manual controller are explained in JavaScript fetch timeout with AbortController. If the search API sometimes fails under load, add a retry for idempotent requests as described in retry with exponential backoff and jitter, but never retry a query the user has already replaced.

Testing debounce and throttle with mock timers

Timing code is easy to get subtly wrong and slow to test with real waits. The built-in Node.js test runner can replace setTimeout and Date with a fake clock that you advance with tick(), so the tests run in milliseconds and are fully deterministic (Node.js test runner: mocking timers):

// timing.test.js - run with: node --test
import { test, mock } from "node:test";
import assert from "node:assert/strict";
import { debounce, throttle } from "./timing.js";

test("debounce calls once with the last arguments after the pause", (t) => {
  t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
  const fn = mock.fn();
  const d = debounce(fn, 300);

  d("a"); t.mock.timers.tick(100);
  d("ab"); t.mock.timers.tick(100);
  d("abc");
  t.mock.timers.tick(299);
  assert.equal(fn.mock.callCount(), 0);   // still waiting

  t.mock.timers.tick(1);
  assert.equal(fn.mock.callCount(), 1);
  assert.deepEqual(fn.mock.calls[0].arguments, ["abc"]);
});

test("leading debounce fires immediately, then ignores the burst", (t) => {
  t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
  const fn = mock.fn();
  const d = debounce(fn, 300, { leading: true });
  d(1); d(2); d(3);
  assert.equal(fn.mock.callCount(), 1);
  t.mock.timers.tick(300);
  d(4);                                    // a new burst after the pause
  assert.equal(fn.mock.callCount(), 2);
  assert.deepEqual(fn.mock.calls.map((c) => c.arguments[0]), [1, 4]);
});

test("cancel and flush", (t) => {
  t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
  const fn = mock.fn();
  const d = debounce(fn, 300);
  d("x"); d.cancel(); t.mock.timers.tick(1000);
  assert.equal(fn.mock.callCount(), 0);
  d("y"); d.flush();
  assert.equal(fn.mock.callCount(), 1);
  t.mock.timers.tick(1000);
  assert.equal(fn.mock.callCount(), 1);    // flushed call is not repeated
});

test("throttle runs at most once per interval, leading and trailing", (t) => {
  t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 });
  const fn = mock.fn();
  const th = throttle(fn, 200);
  for (let ms = 0; ms < 1000; ms += 50) {  // 20 events, every 50 ms
    th(ms);
    t.mock.timers.tick(50);
  }
  t.mock.timers.tick(200);
  assert.deepEqual(fn.mock.calls.map((c) => c.arguments[0]), [0, 150, 350, 550, 750, 950]);
});

test("debounce keeps `this` for object methods", (t) => {
  t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
  const form = {
    saved: null,
    save: debounce(function (value) { this.saved = value; }, 100),
  };
  form.save("draft");
  t.mock.timers.tick(100);
  assert.equal(form.saved, "draft");
});
$ node --test --test-reporter=tap
ok 1 - debounce calls once with the last arguments after the pause
ok 2 - leading debounce fires immediately, then ignores the burst
ok 3 - cancel and flush
ok 4 - throttle runs at most once per interval, leading and trailing
ok 5 - debounce keeps `this` for object methods
# tests 5
# pass 5
# fail 0

One detail in the throttle test: the mocked Date.now() starts at 0, and this throttle stores the time of the last call as 0 too, so the first call would look as if it came too soon. Passing now: 10_000 starts the fake clock at a realistic value. Jest and Vitest offer the same approach with useFakeTimers() and advanceTimersByTime().

Common debounce and throttle bugs

  • Creating a new debounced function on every event or render. input.oninput = () => debounce(search, 300)() makes a fresh timer each time, so nothing is ever debounced. Create the wrapper once and reuse it. In React, keep it in useMemo or useRef and cancel it in the effect cleanup.
  • Debouncing work the user needs to see right away. A typed character must appear instantly; debounce the expensive reaction, such as the search request, not the input itself.
  • Losing the final call. A leading-only throttle drops the last event. Use a trailing call or flush on the final event, such as pointerup.
  • Never firing during non-stop events. A debounced function can be postponed forever while events keep coming. Add a maximum wait or switch to throttle if the user needs periodic updates.
  • Forgetting cleanup. Pending timers survive component unmounts and page transitions in single-page apps. Call cancel() when the element goes away.
  • Picking wait times by guesswork. Around 300 ms for typing and 100 to 200 ms for resize work well for most users; measure with real devices and real typing speed before going much higher.

Debounce vs throttle checklist

  • Final state only: debounce. Continuous feedback: throttle.
  • Screen updates: requestAnimationFrame, not a millisecond throttle.
  • Scroll and touch listeners registered with { passive: true }.
  • Wrapper created once; cancel() on teardown; flush() on submit or leave.
  • Throttle with a trailing call so the last event is not lost.
  • Search requests debounced and stale requests aborted.
  • Native observers used where they fit: IntersectionObserver, ResizeObserver, CSS sticky.
  • Timing logic covered by tests with fake timers.

Want this done on your own server or site?

I am Saizul Amin, a web developer and technical SEO consultant. I set up and harden VPS servers, migrate WordPress sites, fix indexing problems and build automations. See my portfolio or get in touch.

FAQ

What is the difference between debounce and throttle?

Debounce delays a function until events have stopped for a set time, then runs it once with the last arguments. Throttle runs a function at most once per time interval while events keep firing. For 20 events over one second with a 200 ms wait, debounce runs once and throttle about six times.

When should I use debounce instead of throttle?

Use debounce when only the final value matters: search and autocomplete inputs, autosave, form validation and recalculating layout after a resize. Use throttle when the user needs feedback during the action, such as scroll position, dragging or progress indicators.

What is a good debounce delay for a search input?

Around 250 to 400 milliseconds works well for most users. Shorter delays send more requests while the user is still typing; longer delays make the search feel slow. Flush the pending search immediately when the user presses Enter.

Is requestAnimationFrame better than throttle for scroll events?

For visual updates, yes. requestAnimationFrame runs the callback once right before the next paint, so the work matches the display refresh rate exactly. A millisecond-based throttle can run more often than the screen updates or miss frames. For non-visual work such as analytics, a normal throttle is fine.

Should I use Lodash debounce or write my own?

If Lodash is already in your bundle, its debounce and throttle are well tested and support leading, trailing and maxWait options. Otherwise a small implementation like the one in this guide, with cancel and flush and covered by tests, avoids a dependency for about 60 lines of code.

Sources

NEW BLOGS. REAL STRATEGIES. REAL RESULTS.

Join our community and receive powerful SEO tips, web optimization guides, and growth strategies as soon as they’re published.

Don’t just read blogs — stay ahead of the competition.

We don’t spam! Read our privacy policy for more info.

Share.

Comments are closed.