Debouncing and Throttling in JavaScript


When we build web applications, some events like scrolling, resizing, or typing can fire hundreds of times per second. If we handle every single event directly, it can slow down our app.
Thatโs where Debouncing and Throttling come in โ two techniques to control how often a function runs.
The Problem
Imagine youโre typing in a search bar. If the app makes a network request after every keystroke, the server will get overloaded.
Or, imagine tracking the userโs scroll position. Without control, the function may run thousands of times in just a few seconds.
๐ We need a way to limit function calls.
๐ Debouncing
Definition: Debouncing makes sure that a function runs only after a certain time has passed without it being called again.
โ Real-life Example:
- Think about pressing the elevator button. No matter how many times people press it, the elevator comes only once after a pause.
Example in Code:
function debounce(func, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, args), delay);
};
}
// Usage: Search bar
const searchInput = document.getElementById("search");
searchInput.addEventListener("keyup", debounce((e) => {
console.log("Searching for:", e.target.value);
}, 500));
๐ Here, the search happens only when the user stops typing for 500ms.
โณ Throttling
Definition: Throttling makes sure a function runs at most once in a fixed interval, even if the event keeps happening.
โ Real-life Example:
- Think about a speed radar on the road. Even if 100 cars pass per second, the radar only records one car every few seconds.
Example in Code:
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: Scroll tracking
window.addEventListener("scroll", throttle(() => {
console.log("Scroll position:", window.scrollY);
}, 1000));
๐ Here, no matter how much you scroll, the function runs only once every 1 second.
โ๏ธ Debounce vs Throttle
Feature | Debounce ๐ | Throttle โณ |
When it runs | After pause | At regular intervals |
Use Case | Search input, form validation | Scroll tracking, window resize |
Example | Wait until user stops typing | Log scroll every 1 sec |
โ Conclusion
Debouncing waits until things calm down before running.
Throttling allows execution but only at controlled intervals.
Both are must-know techniques to improve performance in real-world apps. Next time you build a search bar or track scrolling, try using one of them! ๐
Subscribe to my newsletter
Read articles from Tvisha Sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
