Debouncing vs Throttling
One concept. 60 seconds. No fluff.
What Are They?
Both are techniques to control how often a function runs. Both are used for performance optimization. But they solve different problems.
Debouncing β Wait until the user stops doing something, then run the function.
Throttling β Run the function at most once every N milliseconds, no matter how often it is triggered.
π Debouncing Explained
Imagine a search bar that fetches results as you type. Without debouncing, it fires an API call on every keystroke. With debouncing, it waits until you stop typing β then fires once.
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
const search = debounce(async (query) => {
const res = await fetch(`/api/search?q=${query}`);
// update UI
}, 300);Use debouncing for: search inputs, form autosave, window resize handlers.
β±οΈ Throttling Explained
Imagine tracking scroll position. Without throttling, the event fires hundreds of times per second. With throttling, it fires at most once every 100ms β smooth and performant.
function throttle(fn, limit) {
let inThrottle = false;
return (...args) => {
if (!inThrottle) {
fn(...args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}
const handleScroll = throttle(() => {
console.log("Scrolled!", window.scrollY);
}, 100);Use throttling for: scroll events, resize events, mousemove, game loops.
When to Use What
| Scenario | Use |
|---|---|
| Search input that calls an API | Debounce |
| Save button that sends a request | Debounce |
| Scrolling to load more content | Throttle |
| Resize event to recalculate layout | Throttle |
| Button to prevent double-click | Debounce |
TL;DR
Debounce β βWait until you are done.β
Throttle β βAt most once per interval.β
In production, use Lodash's _.debounce() and _.throttle() β they handle edge cases.