If youโve ever worked with scroll events, search boxes, or API calls in JavaScript, youโve likely faced the issue of functions running too often and slowing down your app. Thatโs where Throttle and Debounce come to the rescue!
In this blog, Iโll explain the difference between throttle and debounce with real-world examples, code snippets, and when to use each one.
๐น What is Debounce in JavaScript?
Debounce makes sure a function runs only after a certain time has passed since the last call.
๐ Think of typing in a search box. You donโt want to call the API for every single keystroke. Instead, you want to wait until the user stops typing.
โ
Example:
function debounce(func, delay) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), delay);
};
}
const debouncedSearch = debounce(() => {
console.log("Searching...");
}, 1000);
document.getElementById("searchBox").addEventListener("input", debouncedSearch);
๐ Here, the function will run only after the user stops typing for 1 second.
๐น What is Throttle in JavaScript?
Throttle ensures a function executes at most once in a given time frame, no matter how many times itโs triggered.
๐ Think of scrolling. You donโt want to calculate positions on every pixel scroll; instead, you want to run the function once every X ms.
โ
Example:
function throttle(func, delay) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= delay) {
func.apply(this, args);
lastCall = now;
}
};
}
const throttledScroll = throttle(() => {
console.log("Throttled Scroll Event");
}, 2000);
window.addEventListener("scroll", throttledScroll);
๐ Even if you scroll like crazy, this function will fire only once every 2 seconds.
โก Throttle vs Debounce โ Key Differences
Debounce Examples
Search input (API call after typing stops)
Auto-save feature in text editor
Form validation
Throttle Examples
Scroll position tracking
Resizing window events
API rate limiting (avoid hitting server too much)
โ FAQs
Q1. Which is better โ throttle or debounce?
๐ It depends on your use case. Use debounce for waiting (like search), and throttle for limiting (like scroll).
Q2. Can I use libraries instead of writing my own?
๐ Yes! Popular libraries like Lodash provide ready-to-use _.debounce() and _.throttle() functions.
Q3. Does using them improve performance?
๐ Absolutely. They reduce unnecessary executions and make your app smoother.
๐ Conclusion
Both Throttle and Debounce are powerful tools to optimize JavaScript performance.
Use Debounce when you want to wait until the user stops doing something.
Use Throttle when you want to limit execution rate during continuous actions.
By applying them in the right places, youโll make your apps faster, smoother, and more user-friendly. ๐
๐ If you found this blog useful, drop a comment and share it with your fellow developers!
๐ Follow me for more JavaScript tips and tricks.
Top comments (0)