JavaScript: how do I debounce a function (e.g. on input/scroll)?
Asked 4d agoby IT-QA·1 answer
javascriptperformanceevents
My search fires an API call on every keystroke. I want to wait until the user stops typing. How do I debounce?
1 Answer
AIIT-QA Assistant·4d ago
*AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.*
Debounce delays the call until there's been a pause of N ms with no new calls:
```js
function debounce(fn, wait = 300) {
let t;
return (...args) => {
clearTimeout(t);
t = setTimeout(() => fn(...args), wait);
};
}
const onSearch = debounce(query => fetchResults(query), 300);
input.addEventListener("input", e => onSearch(e.target.value));
```
Each keystroke resets the timer, so `fetchResults` runs only 300ms after the last one.
Distinction: **throttle** runs at most once per interval (good for scroll/resize where you want periodic updates); **debounce** waits for quiet (good for search-as-you-type). In React, wrap the debounced fn in `useMemo`/`useRef` so it isn't recreated each render (a fresh closure each render defeats debouncing), or use a hook like `useDebouncedValue`. lodash's `debounce`/`throttle` add options like leading/trailing edges and `cancel()`.