Asynchronous JavaScript

Throttle & Debounce

High-frequency events like scroll, resize, and input can fire hundreds of times per second. Throttle and debounce are two essential techniques to limit how often your handlers run, improving performance and reducing unnecessary API calls.

What is the difference between debounce and throttle?

Both limit how often a function runs during rapid events. Debounce waits until the events stop for a set time, then runs once; it's ideal for search-as-you-type. Throttle runs at most once per interval while events keep firing; it's ideal for scroll and resize handlers.

function debounce(fn, ms) {
  let t;
  return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), ms); };
}
function throttle(fn, ms) {
  let last = 0;
  return (...args) => {
    const now = Date.now();
    if (now - last >= ms) { last = now; fn(...args); }
  };
}
input.addEventListener("input", debounce(search, 300));

Debounce — Wait for silence

Events: ─ A ─ B ─ C ─ ─ ─ ─ D ─ ─ ─ ─
Output: ─ ─ ─ ─ ─ ─ ─ C ─ ─ ─ ─ ─ D ─
↑ fires after 400ms of silence
Cancel timer on every call
Start a new timer for N ms
Only fire when timer expires without cancellation
Leading edge option: fire immediately, then wait

Throttle — Rate limiter

Events: ─ A ─ B ─ C ─ D ─ E ─ F ─ G ─
Output: ─ A ─ ─ ─ C ─ ─ ─ E ─ ─ ─ G ─
↑ fires every 200ms max
Track the timestamp of the last call
Only fire if N ms have elapsed since last call
Evenly distributes calls across time
Trailing option: ensure last call always fires

Real-world Use Cases

DebounceSearch-as-you-type

Only call the API after the user stops typing (400ms silence)

DebounceAuto-save form

Save to server 1s after the user stops making changes

DebounceWindow resize

Recalculate layout 200ms after resize ends, not on every pixel

ThrottleScroll handler

Update sticky header position at most every 100ms

ThrottleMousemove / drag

Track cursor/drag position at most every 16ms (1 frame)

ThrottleClick spam prevention

Prevent form double-submission by throttling to once per 1s

Common Pitfalls

Creating a new debounce/throttle wrapper on every render (e.g. in React) — each render creates a new timer, defeating the purpose
Create the debounced/throttled function ONCE, outside the render or in useMemo/useRef in React
Using debounce for scroll events — user only sees the update after they stop scrolling, causing jank
Use throttle (or rAF throttle) for scroll/resize/mousemove; use debounce only for 'after activity stops'
Not providing a cancel() method — pending timers fire after component unmount causing state updates on dead components
Implement or use a library version with .cancel(). Call it on cleanup (useEffect return / componentWillUnmount)
Setting debounce delay too high (>500ms) for search inputs — users get frustrated waiting for results
200-400ms is usually ideal for search; use 800-1000ms only for auto-save / heavy operations

Interactive Demo

Code Editor

<input id="search" placeholder="Type fast...">
<p>Raw input events: <b id="raw">0</b></p>
<p>Debounced (300ms after you stop): <b id="deb">0</b></p>
<p>Throttled (max once per 500ms): <b id="thr">0</b></p>

Preview

Throttle and debounce — step by step

1 / 4
1

Throttle — execute at most once per interval

Throttle ensures a function fires at most once every N milliseconds, no matter how many times it is called. On scroll or mousemove events that fire hundreds of times per second, throttle keeps execution predictable. The first call fires immediately; subsequent calls within the window are dropped.

1 of 4
💡Always cancel on unmount in React
Store the debounced or throttled function in a ref (useRef) or useMemo so it is not recreated on each render. Return a cleanup function from useEffect that calls cancel() on it — otherwise the callback may fire after the component unmounts, leading to state-update-on-unmounted-component warnings.

🎯 Quick Check

A search input fires an API call on every keystroke. Which technique should you use?

Throttle and Debounce: summary

Key points

  • Debounce: "wait for a pause". Throttle: "no more than once every X ms".
  • A 200–300ms debounce feels responsive for search inputs.
  • For visual updates on scroll, requestAnimationFrame is often better than throttle.

Frequently asked questions

›When should I use debounce?

When you only care about the final value after the user stops: search suggestions, form auto-save, and recalculating on resize end.