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
Debounced search runs fornothing yet
Throttled preview showsnothing yet
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.
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.
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
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.
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
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.