Debounce
Debouncing delays a function until calls have stopped for a chosen amount of time. Every new call resets the timer. The function eventually runs with the most recent arguments.
Implementation
Section titled “Implementation”function debounce(callback, delay) { let timerId;
return function (...args) { clearTimeout(timerId); timerId = setTimeout(() => { callback.apply(this, args); }, delay); };}The returned function remembers timerId between calls. Clearing the previous timer means only the latest call can finish its wait. apply(this, args) passes along the caller’s this value and arguments.
Example: search input
Section titled “Example: search input”const input = document.querySelector('#search');
const runSearch = debounce((query) => { console.log('Search for:', query);}, 500);
input.addEventListener('input', (event) => { runSearch(event.target.value);});If the user keeps typing faster than once every 500 ms, the handler waits. It runs 500 ms after the last input event.
Things to remember
Section titled “Things to remember”- The example runs on the trailing edge: after the pause.
- If events never stop, this implementation never runs. A maximum wait requires an additional rule.
- Debouncing avoids unnecessary calls, but it also adds a delay. Choose the delay based on the interaction.
For the comparison with throttle, see Debounce vs throttle.