JavaScript · Question 7 of 50
What is the difference between debounce and throttle? Write debounce.
What they're checking
Practical performance, plus closures and timers in one go.
The answer
Both limit how often a function runs when an event fires a lot. Debounce waits until the events stop for a set time, then runs once: search-as-you-type, auto-save, the end of a resize. Throttle runs at most once per interval while the events keep coming: scroll position, mouse movement, calls to a rate-limited API.
Debounce is a closure holding a timer: every call clears the old timer and starts a new one.
function debounce(fn, ms) {
let timer
return (...args) => {
clearTimeout(timer)
timer = setTimeout(() => fn(...args), ms)
}
}
const search = debounce((q) => fetchResults(q), 300)The picture
events: │ │ ││││ │ │││ │ │ debounce: ▲ once, after 300 ms of quiet throttle: ▲ ▲ ▲ ▲ at most once per interval
The follow-up they'll ask
Leading or trailing debounce?
Show the answer
Trailing, the default, runs after the burst. Leading runs on the first event and ignores the rest until things go quiet: good for a button that must not submit twice.
Your progress stays on this device.