Learn the concept
Debounce & Throttle
A debounce function delays execution until a pause in calls, using a closure to manage a timer that resets on each invocation. Advanced implementations support leading/trailing edge execution, cancel and flush methods, and a maxWait option to guarantee eventual execution.
What is Debouncing:
Core Implementation:
this context and arguments to the original functionAdvanced Features:
Leading edge: Execute immediately on the first call, then debounce subsequent calls. Useful when you want instant feedback on the first interaction.
Trailing edge: Execute after the wait period (default behavior). Both leading and trailing can be enabled simultaneously.
Cancel: Abort any pending invocation by clearing the timer. Critical for cleanup in component unmount scenarios.
Flush: Immediately invoke the pending function if one exists. Useful for form submission where you need the latest value now.
maxWait: Guarantee the function is called at least once every maxWait milliseconds, even if calls keep coming. Prevents the debounced function from being delayed indefinitely.
Key Interview Points:
this binding via .apply() or .call()function debounce(func, wait) {
let timeoutId = null;
return function debounced(...args) {
// Clear any pending timer
clearTimeout(timeoutId);
// Set a new timer that calls func after wait ms
timeoutId = setTimeout(() => {
func.apply(this, args);
timeoutId = null;
}, wait);
};
}
// Usage
const handleSearch = debounce((query) => {
console.log('Searching for:', query);
fetch(`/api/search?q=${query}`);
}, 300);
// Rapid calls — only the last one executes
handleSearch('h'); // cancelled
handleSearch('he'); // cancelled
handleSearch('hel'); // cancelled
handleSearch('hello'); // executes after 300msDebouncing search input to avoid firing API requests on every keystroke, waiting until the user pauses typing before querying the server
Debouncing resize event listeners to recalculate layouts only after the user finishes resizing, preventing expensive reflows on every pixel change
Debouncing document changes in text editors to save drafts only after the user stops typing, reducing unnecessary write operations and API calls
Implement a complete debounce utility with leading, trailing, maxWait, cancel, flush, and pending methods with comprehensive tests covering edge cases
Build a React autocomplete input that debounces API requests, shows loading states, handles race conditions with AbortController, and highlights matching text