π§ Understanding Debounce and Throttle in JavaScript β With Real Use Cases

In modern web apps, performance is everything. When working with events like typing, scrolling, or resizing, calling a function too frequently can slow down your app. Thatβs where debouncing and throttling come in.
π What is Debouncing?
Debounce delays the execution of a function until a specified time has passed since the last time it was invoked.
π Use Case:
Search input fields
Form validation on typing
β Example:
javascriptCopyEditfunction debounce(func, delay) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
// Usage
const handleSearch = debounce(() => {
console.log("Searching...");
}, 500);
β±οΈ What is Throttling?
Throttle ensures that a function is only called once every X milliseconds, no matter how often the event is triggered.
π Use Case:
Scroll events
Window resize
β Example:
javascriptCopyEditfunction throttle(func, limit) {
let lastFunc;
let lastRan;
return function (...args) {
const context = this;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(function () {
if ((Date.now() - lastRan) >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
}
// Usage
const handleScroll = throttle(() => {
console.log("Scrolling...");
}, 200);
π§ Key Differences
Feature | Debounce | Throttle |
Frequency | Only after event stops | At regular intervals |
Use Case | Typing, search, resize | Scrolling, mouse move |
Example | Auto-suggest field | Infinite scroll pagination |
β When to Use Each?
Debounce: When you want to limit how often a function is called after an event finishes (e.g., typing).
Throttle: When you want to limit how often a function is called while the event is running (e.g., scrolling).
π Conclusion
Debouncing and throttling are crucial for creating smooth and optimized web experiences. By understanding when and how to use them, youβll write cleaner, faster, and more efficient code.
Subscribe to my newsletter
Read articles from Noura Mostafa directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Noura Mostafa
Noura Mostafa
π Aspiring Full-Stack Developer Blogger π¨βπ» Passionate about web development and coding. βοΈ Sharing my journey through tech via CodeOdyssey π "The code is a journey, not a destination."