Debounce · JavaScript

Also known as: debouncing

On this page 7

Debounce in JavaScript is a technique that delays running a function until a burst of events has stopped for a defined quiet period, so that many rapid triggers produce a single call. In Browser JavaScript, debouncing is applied to high-frequency events such as typing, window resizing and scrolling, where reacting to every event would waste CPU time, network requests or rendering work.

Each new event cancels the pending timer and starts a new one. The wrapped function runs only when the timer is allowed to expire, which means it reacts to the final state of a sequence rather than to each intermediate step.

How a debounced function works

A debounced function is a wrapper around the original function that keeps a timer identifier in a closure. On every call, the wrapper runs clearTimeout on the previous timer and schedules a new one with setTimeout. If no further call arrives within the wait interval, the timer fires and the original function runs with the most recent arguments.

The timer callback is a macrotask placed on the task queue by the event loop, so the actual call happens asynchronously after the current script finishes. This is why a debounced handler never runs synchronously inside the event that triggered it, and why its this value and arguments must be captured explicitly by the wrapper.

The sequence below shows what a debounced search handler with a 300 ms wait does as a user types the word “lamp”.

TimeEventTimer actionFunction runs
0 msKey lStart 300 ms timerNo
120 msKey aCancel, restart timerNo
210 msKey mCancel, restart timerNo
330 msKey pCancel, restart timerNo
630 msNo inputTimer expiresYes, once, with lamp
Timeline of a debounced keystroke handler

Four events produced one function call, and the call used the final input value. Without debouncing, the same typing would have triggered four handler runs and potentially four network requests.

Leading, trailing and maximum wait options

Debounce implementations differ in when the call happens relative to the burst. The default is trailing-edge execution, but many utility libraries also offer leading-edge execution and a maximum wait that guarantees progress during an endless stream of events.

VariantWhen the function runsTypical useMain drawback
Trailing edgeAfter the quiet period endsSearch suggestions, form validationFeedback arrives only after a pause
Leading edgeOn the first event, then ignores the burstPreventing double submission of a buttonMisses the final state of the burst
Leading and trailingAt the start and after the burstResponsive yet accurate UI updatesUp to two calls per burst
Max waitAt least once per maximum intervalAutosave during continuous typingMore calls than plain debounce
Debounce variants and their behavior

A practical implementation also exposes cancel and flush methods. cancel discards a pending call, which is useful when a component is removed, and flush runs the pending call immediately, which is useful before navigation or form submission so that the last input is not lost.

Debounce compared with throttle and other rate control

Debounce is often confused with throttle, but the two answer different questions. Debounce waits for activity to stop, while throttle guarantees at most one call per interval during continuous activity. Browser APIs such as requestAnimationFrame and the Intersection Observer API provide further, more specialized forms of rate control.

TechniqueCall patternBest fitWeak fit
DebounceOnce after events stopText input, resize end, autosaveSmooth scroll-linked animation
ThrottleRegular calls at a fixed rateScroll position tracking, drag updatesActing only on final input
requestAnimationFrameOnce per display frameVisual updates tied to renderingNetwork requests
Intersection Observer APIWhen visibility thresholds changeLazy loading, infinite listsArbitrary event streams
Rate control techniques in the browser

A simple rule separates them: if only the end result of a burst matters, use debounce; if the user needs continuous feedback while the burst continues, use throttle or a frame-based approach.

Choosing the wait interval

The wait interval is a trade-off between responsiveness and efficiency. A short interval feels immediate but lets more calls through; a long interval saves work but makes the interface feel sluggish. Values between 150 and 500 ms cover most interactive cases, and the right number depends on how fast users produce events and how expensive each call is.

SituationTypical waitReason
Search-as-you-type suggestions200 to 300 msMatches pauses between typed words
Form field validation300 to 500 msAvoids error messages while typing
Window resize recalculation100 to 250 msLayout work is expensive
Autosave of a draft1 to 2 s, with max waitLimits writes but keeps data safe
Typical wait intervals by situation

Intervals should be validated with real user input, including slow typists and mobile keyboards, because a value that feels right to a developer may trigger premature requests for other users.

Common pitfalls when debouncing

Most debounce bugs come from creating the wrapper in the wrong place or forgetting that the call is asynchronous. The following list covers the problems seen most often in production code.

  • Recreating the wrapper on every render in component frameworks resets the timer each time, so the function either never runs or runs on every event.
  • Losing the event object happens when code reads properties after the timer fires; synthetic or reused events may no longer hold the values, so copy the needed values first.
  • Stale responses can arrive out of order even with debouncing; combine it with an AbortController to cancel outdated fetch requests.
  • Missing cleanup leaves a pending timer after a component or event listener is removed, which may update state that no longer exists.
  • Debouncing critical actions such as payment buttons with a trailing edge delays the action; use leading-edge debounce or disable the button instead.

Debounce also does not reduce event delivery itself. The browser still dispatches every event to the listener; only the expensive work is postponed. For very frequent events, a passive event listener remains useful alongside debouncing.

In plain words

Debounce means waiting until someone has finished before reacting. Imagine an elevator door that stays open while people keep stepping in and closes only after nobody has entered for a few seconds.

On a website, a search box works the same way. Instead of searching after every single letter, the page waits for a short pause in typing and then searches once. The result is fewer wasted requests and a smoother page.

A real-world example

An online hardware store adds live product suggestions to its search box. In the first version, every keystroke sends a request to the suggestion service, and a shopper typing “cordless drill” produces 14 requests in about two seconds, several of which return out of order and briefly show wrong suggestions.

The frontend team wraps the input handler in a trailing debounce of 250 ms and cancels outdated requests with an AbortController. The same query now produces one or two requests, the suggestion list no longer flickers, and the load on the suggestion service during busy periods drops by roughly 80 percent.