If you work with JavaScript long enough, you’ll face this problem:
Some events fire too frequently.
Examples:
-
input→ every key press -
scroll→ dozens of times per second -
resize→ continuously while dragging the window
If you run expensive logic on every event, performance suffers.
That’s where debounce and throttle come in.
Let’s understand both with plain JavaScript and simple examples.
Debounce — Run after the user stops
Debounce delays the execution of a function until the user stops triggering an event for a specified time.
Common use cases
- Search input
- Form validation
- Auto-save
- API calls on typing
Debounce — JavaScript Implementation
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn(...args);
}, delay);
};
}
Usage example (search input)
const search = debounce((text) => {
console.log("Searching for:", text);
}, 500);
input.addEventListener("input", (e) => {
search(e.target.value);
});
What’s happening?
- Every keystroke clears the previous timer
- A new timer starts
- If the user keeps typing → function never runs
- Once typing stops → function runs once
Throttle — Run at fixed intervals
Throttle ensures a function runs at most once every X milliseconds, no matter how many times the event fires.
Common use cases
- Scroll events
- Resize events
- Drag & drop
- Preventing button spam
Throttle — JavaScript Implementation
function throttle(fn, limit) {
let isLocked = false;
return function (...args) {
if (isLocked) return;
fn(...args);
isLocked = true;
setTimeout(() => {
isLocked = false;
}, limit);
};
}
Usage example (scroll)
const handleScroll = throttle(() => {
console.log("Scrolling...");
}, 1000);
window.addEventListener("scroll", handleScroll);
What’s happening?
- First event runs immediately
- Function gets locked
- All events during the lock are ignored
- Function unlocks after the time limit
Debounce vs Throttle (Quick Comparison)
| Feature | Debounce | Throttle |
|---|---|---|
| When function runs | After user stops | At fixed intervals |
| Extra events | Cancelled | Ignored |
| Execution style | Delayed | Immediate |
| Best for | Input, search | Scroll, resize |
Easy way to remember
Debounce → clear + wait
Throttle → lock + release
Final Thoughts
Debounce and throttle are small utilities, but they make a huge difference in:
- performance
- user experience
- API efficiency
If you understand when to use which, you’re already writing better JavaScript than most.
Happy coding
