Debouncing vs. Throttling
Both techniques are used to control how many times a function is executed over time, especially for events that fire rapidly (like scrolling or resizing).
1. The Analogies
Debouncing: The Elevator Door
Imagine you are in an Elevator.
- A person enters. The door starts to close in 5 seconds.
- If another person enters before the 5 seconds are up, the timer restarts.
- The elevator only starts moving after the last person has entered and the full 5 seconds have passed without anyone else coming.
Coding Example: Search Bar. You only send an API request after the user stops typing for 500ms.
Throttling: The Traffic Light
Imagine a Traffic Light.
- It turns green every 60 seconds, regardless of how many cars are waiting.
- It doesn't matter if 1 car or 100 cars arrive; it will only let them pass once every minute.
Coding Example: Scrolling. You only update the position of an element every 100ms while the user scrolls, not for every pixel of movement.
2. Coding Examples
Debounce (Wait for silence)
function debounce(func, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), delay);
};
}Throttle (Keep a steady pace)
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}Summary
| Technique | Goal | Analogy |
|---|---|---|
| Debounce | Group multiple signals into one | Elevator Door |
| Throttle | Limit the rate of execution | Traffic Light |
Use Debounce for inputs and Throttle for movement events!