Debounce
When to Use Debounce
In Practice
useDebouncedValue for this. Different from throttle (throttle still fires periodically).Sketch
JavaScript
function debounce(fn, ms) {
let t;
return (...args) => {
clearTimeout(t);
t = setTimeout(() => fn(...args), ms);
};
}How Debounce Comes Up in Interviews
Scenario
You're wiring up a search-as-you-type box. You want exactly one API call to fire after the user stops typing for 300ms, and you want to drop every keystroke in between. Which technique?
Debounce waits for a quiet period of N ms before firing once, exactly the 'stop typing then search' pattern. Throttle would still fire periodically while the user types.
Debounce defers an action until events stop arriving for a quiet period, the standard 'wait until the user pauses typing before searching' pattern. Implementation is trivial (reset a timeout on each event), but the choice between leading-edge debounce (fire immediately, ignore the rest) and trailing-edge (wait for quiet, then fire once) is application-specific. React's useDebouncedValue and Lodash's _.debounce default to trailing-edge with leading as an option. Throttle is the wrong shape here because it still fires periodically while the user types, generating wasted requests for every interim keystroke.