How do I debounce an input handler in JavaScript?
A search box fires an API request on every keystroke. I want the request to run only after the user pauses typing.

Answer
Debouncing delays a function until a quiet period has passed since the last call. Each new call cancels the pending timer and starts a new one.
- Pick a delay between 150 and 400 ms for search boxes.
- Keep the timer id in a closure so every call shares it.
- Use `AbortController` on the fetch itself if slow responses can arrive out of order.
For scroll and resize handlers you usually want *throttling* instead, which runs at most once per interval.
JavaScript solution
function debounce(fn, delay = 300) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
const input = document.querySelector('#search');
const onType = debounce(async (event) => {
const q = event.target.value.trim();
if (!q) return;
const res = await fetch(`/api/search?q=${encodeURIComponent(q)}`);
console.log(await res.json());
}, 250);
input.addEventListener('input', onType);Edited by Jack · joysait@rediffmail.com