Debounce vs Throttle in JavaScript: When to Use Each With Examples
Debounce waits for inactivity before firing. Throttle fires at regular intervals during activity. Wrong choice causes laggy UIs or missed events. Here is how to pick the right one.
Debounce and throttle are essential for controlling how often expensive functions run.
Debounce — Wait for Silence
Delays execution until there is a pause in events. Resets the timer on each new event.
function debounce(fn: Function, ms: number) {
let timer: NodeJS.Timeout;
return (...args: any[]) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}// Use for: search input, window resize, form validation const handleSearch = debounce((query: string) => { fetchResults(query); }, 300); ```
Throttle — Fire at Intervals
Executes at most once per interval, no matter how many events fire.
function throttle(fn: Function, ms: number) {
let lastCall = 0;
return (...args: any[]) => {
const now = Date.now();
if (now - lastCall >= ms) {
lastCall = now;
fn(...args);
}
};
}// Use for: scroll events, mouse move, analytics tracking const handleScroll = throttle(() => { updateScrollPosition(); }, 100); ```
Quick Decision Guide
- ●Search input: Debounce (wait until user stops typing)
- ●Scroll handler: Throttle (fire at regular intervals)
- ●Window resize: Debounce (wait until resize ends)
- ●Button spam: Throttle (allow once per second)
- ●Auto-save: Debounce (save after user stops editing)
Learn more at our web development services.
Written by M Daniyal Amjad Ali
Full Stack Software Engineer with 5+ years of experience. Expert in Next.js, React, Node.js, and Prisma. 100+ projects delivered worldwide.