This content originally appeared on DEV Community and was authored by Dakshim Chhabra
If you’ve ever built a search box with autocomplete, infinite scroll, or live typing app, you’ve probably run into performance issues when functions fire too many times.
Yes, that’s annoying, but how to tackle the same?
That’s where Debouncing
and Throttling
come in. These two techniques help control how often a function executes in response to frequent events like typing, scrolling, or resizing.
Debounce
Debouncing makes sure your function only executes after a certain period of inactivity.
Think of a doorbell:
If someone keeps pressing it rapidly, you don’t want it ringing every single time. Instead, ideally it should ring once, the user stop pressing button.
Javascript Implementation
function debounce(fn, delay) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId); // reset timer if function called again
timeoutId = setTimeout(() => {
fn.apply(this, args); // run after delay
}, delay);
};
}
Where to use Debounce
- Search boxes with auto-suggestions
- Form validations
- Window resize events
Throttle
Throttling ensures your function executes at most once every X milliseconds or specific time after a certain number of events, no matter how many times it’s triggered.
Say, you want to implement a scroll-based animation, you don’t want to read every scroll event.
or
Think of a security guard at a gate:
Even if a crowd keeps pushing, the guard only lets 1 person in every 5 seconds.
Javascript Implementation
function throttle(fn, limit) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= limit) {
lastCall = now;
fn.apply(this, args);
}
};
}
Where to use Throttle
- Scroll events (infinite scroll, lazy loading)
- Button clicks
- Drag-and-drop actions
Final Thoughts
Both Debouncing and Throttling are essential for building high-performance, user-friendly apps.
Use Debounce
when you want to wait until the user has finished doing something.
Use Throttle
when you want to control execution frequency over time.
Master these two techniques, and your app (and your users!) will thank you.
p.s. above functions are just for knowledge, I use rxjs
or lodash
to implement debounce and throttle in ReactJs projects.
Have you used Debounce or Throttle in your projects? Share your favorite use case in the comments!
This content originally appeared on DEV Community and was authored by Dakshim Chhabra