Last updated: August 28, 2026.
The input event can fire for every keystroke. Debouncing cancels the previous timer and runs the function only after the user pauses for a short interval.
Create a reusable debounce helper
function debounce(callback, delay = 250) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => callback.apply(this, args), delay);
};
}
const search = document.querySelector('#search');
search.addEventListener('input', debounce(event => {
console.log('Search for:', event.target.value.trim());
}, 300));Avoid stale network results
- Cancel the previous fetch with AbortController.
- Show progress only for the active request.
- Choose a short delay for local work and a longer one for remote search.
- Run final validation again when the form submits.
Reference: MDN setTimeout reference.