- Регистрация
- 9 Май 2015
- Сообщения
- 1,574
- Баллы
- 155
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?
?
! 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.
Read writing from ? Rohit Singh ? on Medium. Full-stack developer with 6+ years in Angular, Node.js & AWS. Sharing tips, best practices & real-world lessons from building scalable apps.
medium.com
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.
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.
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.
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)
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?
?
! 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.
Read writing from ? Rohit Singh ? on Medium. Full-stack developer with 6+ years in Angular, Node.js & AWS. Sharing tips, best practices & real-world lessons from building scalable apps.
Источник: