Some browser events fire far more often than you might expect. Scrolling a page can trigger dozens of scroll events per second. Typing a single word in a search box fires an input event for every keystroke. Resizing a window produces a steady stream of resize events. If each event runs an expensive task, such as calling an API or recalculating a layout, your page can become slow and wasteful. Two classic techniques solve this problem: debounce and throttle. In this article, you will learn what each one does, how to write them in plain JavaScript, and how to choose the right one.
The problem: too many function calls
Consider a search field that suggests results as the user types. A naive implementation sends a request on every keystroke:
searchInput.addEventListener('input', (event) => {
fetchSuggestions(event.target.value);
});
If someone types “javascript,” that is ten requests, and most of them are useless because the user has not finished typing. The server does extra work, the network is busier than it needs to be, and responses may even arrive out of order. Debounce and throttle both reduce how often a function runs, but they do it in different ways.
What is debounce?
Debouncing delays a function until a certain amount of time has passed without the event firing again. Every new event resets the timer. The function only runs once the activity stops.
A helpful analogy is an elevator door. Each time someone walks in, the door waits a little longer before closing. It only closes when nobody has entered for a few seconds.
Here is a simple debounce function:
function debounce(fn, delay) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
And here is how you would use it in the search example:
const debouncedFetch = debounce((value) => {
fetchSuggestions(value);
}, 300);
searchInput.addEventListener('input', (event) => {
debouncedFetch(event.target.value);
});
Now the request is only sent when the user pauses typing for 300 milliseconds. A fast typist who enters a whole word in one burst triggers a single request instead of many.
What is throttle?
Throttling guarantees that a function runs at most once in a given time interval, no matter how many times the event fires. Unlike debounce, it keeps running regularly while the activity continues.
Think of a security guard who lets one person through a gate every two seconds. People can keep arriving, but the flow is limited to a steady rate.
A basic throttle function looks like this:
function throttle(fn, interval) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= interval) {
lastCall = now;
fn.apply(this, args);
}
};
}
A typical use is tracking scroll position, for example to show a “back to top” button or update a reading progress bar:
const onScroll = throttle(() => {
updateProgressBar(window.scrollY);
}, 100);
window.addEventListener('scroll', onScroll);
The progress bar updates up to ten times per second while the user scrolls, which feels smooth without running the code on every single event.
Note that this simple version runs the function immediately on the first event and then ignores calls until the interval passes. That means the very last event may be skipped. More complete implementations add a final “trailing” call so the end state is always captured.
Debounce vs. throttle at a glance
| Aspect | Debounce | Throttle |
|---|---|---|
| When the function runs | After the events stop for a set time | At regular intervals while events continue |
| During continuous activity | Does not run until activity ends | Runs periodically |
| Best for | Reacting to the final value | Reacting steadily during activity |
| Common examples | Search suggestions, form validation, auto-saving drafts | Scroll tracking, infinite scroll checks, mouse movement, game input |
How to choose the right technique
A simple question usually settles it: do you care about the final result or about regular updates along the way?
- Choose debounce when only the end of the activity matters. Validating an email field after the user stops typing, saving a draft after a pause, or recalculating a layout once the window has finished resizing are good examples.
- Choose throttle when the user expects continuous feedback. Updating the position of an element while dragging, checking whether the user has scrolled near the bottom of a list, or limiting how fast a button can trigger an action all benefit from throttling.
Choosing a good delay
There is no single correct value. For typing, delays between roughly 200 and 500 milliseconds are common: short enough to feel responsive, long enough to skip most keystrokes. For scroll and mouse events, intervals around 100 milliseconds or less usually feel smooth. The best approach is to test with real users and adjust. A delay that is too long makes the interface feel sluggish; one that is too short brings back the original performance problem.
Practical tips
- Create the wrapped function once. Calling
debounce()inside the event handler creates a new timer every time and breaks the behavior. Wrap the function outside the listener, as in the examples above. - Consider existing utilities. Libraries such as Lodash provide well-tested
debounceandthrottlefunctions with extra options, like leading and trailing calls and cancellation. - Clean up in components. In frameworks such as React or Vue, cancel pending timers when a component is removed to avoid running code on elements that no longer exist.
- Look for native alternatives. For visual updates tied to animation,
requestAnimationFramecan be a better fit. To detect when elements enter the screen, theIntersectionObserverAPI often replaces throttled scroll listeners entirely.
Conclusion
Debounce and throttle are small functions with a big impact on performance and user experience. Debounce waits for the activity to stop and then acts once; throttle acts at a steady pace while the activity continues. Knowing the difference helps you build interfaces that feel fast, use fewer resources, and put less load on your servers.
If you want to keep building your front-end skills, check out the free Web Development courses on Cursa and practice these techniques in your own projects.







