When working with user events like scrolling, resizing, or typing in a search box, your functions might run too frequently, which can slow down your app.
That’s where Debouncing and Throttling come to the rescue!
In this blog, let’s break down both concepts with simple, real-life examples to help you understand when and how to use them.
What is Debouncing?
Debouncing is a technique where a function is delayed until a certain amount of time has passed since the last event. It's useful for events like typing, where you only want to react after the user has finished.
Real-Life Example of Debouncing
- When you type a product name in the search bar of an e-commerce site, it doesn’t make a request after every letter you type.
- Instead, it waits until you pause typing for a moment, and then shows suggestions.
- This helps reduce the number of unnecessary API calls and improves performance — a perfect use case for debouncing.
Use Cases of Debouncing
- Search Input: Reduce API calls while the user is typing.
- Auto-Suggestions / Autocomplete: Wait for the user to stop typing before fetching or showing suggestions.
- Resize Window: Prevent repeated function calls during continuous resizing.
- Real-Time Form Validation: Validate input fields after the user stops typing.
- Auto-Saving Drafts: Save the content after a short pause instead of on every keystroke.
- Scroll-Based Lazy Loading: Load more content after scrolling stops (less common but useful in some cases).
- Prevent Multiple Button Clicks: Avoid multiple submissions by debouncing click events.
Code Example: Debouncing in JavaScript
function debounce(func, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
// Usage
const handleInput = debounce(() => {
console.log("Searching...");
}, 300);
document.getElementById("search").addEventListener("input", handleInput);
In this example, the search input uses a debounce function to delay execution. Instead of running the handleInput function on every keystroke, it waits 300ms after the user stops typing. If the user types continuously, the timer resets each time.
This way, the function runs only once after typing ends, reducing unnecessary calls (like API requests) and improving performance. It's a common technique used in search bars, filters, and live suggestions.
What is Throttling?
Throttling is a technique where a function is allowed to run only once in a specific time interval, no matter how many times the event is triggered during that time.
It’s useful for events that can fire continuously — like scrolling, resizing, or mouse movements — where you want to limit the number of times the function runs.
Real-Life Example of Throttling
- Imagine you're at a toll booth where only one car is allowed to pass every 5 seconds, no matter how many cars are lined up.
Even if cars keep coming rapidly, only one gets through at a time, at a fixed rate.
- That’s how throttling works.
Use Cases of Throttling
- Scroll Events: Limit the number of times a scroll handler is called while the user is scrolling.
- Window Resize: Avoid running heavy layout calculations too often during continuous resizing.
- Button Clicks / Repeated Triggers: Limit how often a button’s click handler runs if the user clicks too quickly.
- Mouse Move Events: Control how frequently the function reacts to mouse movements (e.g., in games or drag-and-drop).
- API Rate Limiting (Client Side): Send data at fixed intervals, even if the user generates input faster.
Code Example: Throttling in JavaScript
function throttle(func, limit) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= limit) {
lastCall = now;
func.apply(this, args);
}
};
}
// Usage
const handleScroll = throttle(() => {
console.log("Scrolling...");
}, 1000);
window.addEventListener("scroll", handleScroll);
In this example, we add a scroll event listener to the window. The handleScroll function is wrapped with a throttle, allowing it to run only once every 1000ms (1 second) — no matter how many times the user scrolls.
So if the user scrolls rapidly, the function won’t run for each scroll event. Instead, it runs at a controlled pace, which helps reduce performance issues caused by too many function calls
This approach is very useful in creating smooth scrolling experiences, infinite scrolling, and responsive UI behaviors.
When to Use What?
- Use debouncing for actions like typing in a search box or resizing the window, where you only care about the final result.
- Use throttling for actions like scrolling, dragging, or mouse movements, where you want regular updates but not too many.
Summary
In this blog, we learned how debouncing and throttling are simple yet effective techniques to control how often functions run during frequent user interactions.
- Debounce: Waits for the user to stop triggering an event, then runs the function once.
- Throttle: Runs the function at regular intervals, even while the event keeps firing.
These methods help you avoid performance issues, reduce unnecessary function calls, and create a smoother user experience, especially for actions like typing, scrolling, resizing, and clicking.
Start using debounce and throttle to make your JavaScript apps faster and more efficient!
If you found this helpful, feel free to like, share, or drop your feedback in the comments.