Debounce vs Throttle in JavaScript (Explained Simply with Code)
Source: Dev.to

If you work with JavaScript long enough, you’ll encounter events that fire too frequently—e.g., input on every key press, scroll dozens of times per second, or resize continuously while dragging the window. Running expensive logic on every event hurts performance. This is where debounce and throttle come in.
Debounce — Run after the user stops
Debounce delays the execution of a function until the user stops triggering an event for a specified amount of time.
Common use cases
- Search input
- Form validation
- Auto‑save
- API calls while typing
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, the function never runs.
- Once typing stops, the function runs once.
Throttle — Run at fixed intervals
Throttle ensures a function runs at most once every X milliseconds, regardless of how many times the event fires.
Common use cases
- Scroll events
- Resize events
- Drag & drop
- Preventing button spam
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?
- The first event runs immediately.
- The function becomes locked.
- All events during the lock are ignored.
- The function unlocks after the time limit, allowing the next call.
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
Understanding when to use which helps you write better, more responsive JavaScript.
Happy coding!