Learn the concept
Debounce & Throttle
Debounce delays execution until a pause in activity (e.g., wait 300ms after the user stops typing). Throttle limits execution to at most once per time interval (e.g., at most once every 200ms during scrolling). Both are used to control how often expensive functions run.
Both debounce and throttle control function execution frequency, but they work differently:
Debounce:
Throttle:
Key difference:
Note: The basic throttle implementation below is leading-edge only (executes on the first call). Production throttles (e.g., lodash _.throttle) also support a trailing-edge call so the last event is never silently dropped.
function debounce(fn, delay) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn.apply(this, args), delay);
};
}
// Usage: search input
const searchInput = document.querySelector('#search');
const handleSearch = debounce((query) => {
console.log('Searching for:', query);
// fetch(`/api/search?q=${query}`)...
}, 300);
searchInput.addEventListener('input', (e) => {
handleSearch(e.target.value);
});
// Only fires 300ms after the user stops typingDebouncing search input to reduce API calls while the user types, only firing after they pause
Throttling scroll handlers for sticky headers, parallax effects, and infinite scroll to limit DOM calculations
Debouncing resize handlers to recalculate layouts only after the user finishes resizing the window
Build a search input that debounces API calls and displays autocomplete suggestions with loading state
Build a content feed with throttled scroll detection for lazy loading new items as the user scrolls