Careeroza
What is Debouncing?
Definition
Debouncing waits until the user stops doing something for a set time before running a function. Typing "react" in a search box should send one request, not five.
Keys: r e a c t ............ (pause 500 ms) Without: ↑ ↑ ↑ ↑ ↑ 5 API calls Debounced: ↑ 1 API call
Debounce Function
Example
Each call resets the timer; only the last call within the wait time runs.
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
const search = debounce((q) => console.log('API call for:', q), 100);
search('r');
search('re');
search('rea');
search('react'); // only this one runsOutput
API call for: react