Skip to content
JS-04Intermediate5 min read

Debounce and throttle

Control how often expensive work runs in response to fast events like typing, scrolling and resizing.

Updated

Some events fire far more often than you need them to. Someone typing a search query can trigger dozens of input events per second, and scrolling or resizing can fire on every frame. Debouncing and throttling decide how often your expensive code actually runs in response.

See the difference

Wait
Keystrokes0
Debounced0
Throttled0

Debounced search runs fornothing yet

Throttled preview showsnothing yet

Debounce and throttle, side by sideType in the field. Gray dots are raw keystrokes, blue dots are debounced calls and green dots are throttled calls. Change the wait and type again.

Debounce waits for a pause

A debounced function postpones its work until the events stop for a given amount of time. Every new event restarts the timer, so the work runs once, after the burst is over. Reach for it when only the final value matters.

  • Search as you type: query the server once the user stops typing.
  • Autosave: save a document a moment after the last edit.
  • Validation: check whether a username is available when the user pauses.
debounce.js
export function debounce(fn, wait) {
  let timer

  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => fn(...args), wait)
  }
}

Throttle runs at a steady rate

A throttled function runs at most once per interval, however many events arrive. A trailing call makes sure the last event is never lost. It suits work that should keep updating while the events continue.

  • Scroll effects: progress bars and sticky headers that react to the scroll position.
  • Collaboration: sending cursor positions to other people in a shared document.
  • Resizing: redrawing a chart while the window is being dragged.
throttle.js
export function throttle(fn, wait) {
  let last = 0
  let trailing

  return (...args) => {
    const remaining = wait - (Date.now() - last)

    if (remaining <= 0) {
      last = Date.now()
      fn(...args)
    } else {
      clearTimeout(trailing)
      trailing = setTimeout(() => {
        last = Date.now()
        fn(...args)
      }, remaining)
    }
  }
}

Choosing between them

QuestionDebounceThrottle
When does it run?After the events stop for the waitAt most once per wait, during the events
Runs while events continue?NoYes
Typical wait200 to 500 ms50 to 200 ms, or one animation frame
Good forSearch, autosave, validationScroll, resize, pointer tracking

Using it in React

Create the debounced function once rather than on every render. If you call debounce directly in the component body, every keystroke gets a brand new timer and nothing is ever delayed.

search-box.tsx
function SearchBox({ onSearch }: { onSearch: (query: string) => void }) {
  const debouncedSearch = useMemo(() => debounce(onSearch, 300), [onSearch])

  return (
    <input
      type='search'
      aria-label='Search lessons'
      placeholder='Search lessons'
      onChange={(event) => debouncedSearch(event.target.value)}
    />
  )
}

Try it yourself

debounce.js

Press Control or Command with Enter to run the code. Tab inserts spaces; press Escape and then Tab to leave the editor.

Console

Run the code to see its output here.

Only one search runs, for the full word. Change the wait from 200 to 20 and run it again to see every prefix.

Summary

  • Debounce runs once after a burst of events ends.
  • Throttle runs at a steady rate while events keep coming.
  • Create the wrapped function once per component, not once per render.
  • Always clean up timers when the component that created them unmounts.

Finished this lesson?

Mark it complete to track your progress across every track in the curriculum.