Topic 32 of 37
Debouncing & Throttling
Overview
When users perform actions that fire rapidly (like scrolling, resizing the window, or typing in a search box), attaching heavy functions to these events ruins performance. Debouncing groups rapid events into a single execution at the END. Throttling guarantees execution at regular intervals (e.g., once every 300ms).
Syntax
The closure retains the timeoutId. Every new keystroke resets the clock.
Writing a Debounce Function
javascript
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId); // Cancel previous timer
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
// Usage: only fetches 500ms AFTER user stops typing
const handleSearch = debounce((q) => fetchApi(q), 500);Writing a Throttle Function
javascript
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
// Usage: Fires AT MOST once every 100ms while scrolling
window.addEventListener('scroll', throttle(handleScroll, 100));Common Pitfalls
- Re-creating the debounce function on every render in React. It must be wrapped in a useCallback or useRef so it persists.
Interview Tips
- This is one of the most common Machine Coding questions. Memorize the difference: Debounce is 'Wait for it to stop', Throttle is 'Fire at a steady rhythm'.
Real-World Example
Auto-saving a document while a user types.
example
javascript
// You don't want an API call on every keystroke!
const saveDoc = debounce((content) => {
api.save(content);
}, 1000);