Debounce is a programming technique used to control the rate at which a function executes in response to rapid, repeated events. It ensures that a specific function is invoked only after a defined period of inactivity, preventing it from being called too frequently within a short time span. How It Works:
- A debounced function waits for a specified time (delay) after the last event before executing.
- If another event occurs during the delay, the timer resets, and the waiting period starts again.
- This continues until no further events occur within the delay period.
Common Use Cases:
- Search Boxes: Prevent sending multiple API calls as the user types in a search field.
- Resize Events: Avoid excessive recalculations during a window resize.
- Button Clicks: Prevent multiple actions triggered by rapid button clicks.
- Scrolling: Optimize expensive computations (like animations or API calls) tied to scroll events.
Simple JavaScript example:
function debounce(func, delay) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
// Usage
const log = () => console.log('Debounced!');
const debouncedLog = debounce(log, 1000);
// after called multiple times in rapid succession, it only logs once after 1 second of inactivity
debouncedLog();
debouncedLog();
debouncedLog();