JavaScript Tutorial in Hindi #34 | Debouncing vs Throttling in JS (2025)
✅ 1. What is Debouncing?
- Debouncing delays the execution of a function until a certain time has passed after the last event.
- If the event keeps firing, the function won’t run until the events stop for that delay time.
- Used to limit how often a function runs when triggered frequently (like typing or resizing).
Example Use: Search input box — wait until user stops typing before sending a search query.
✅ 2. What is Throttling?
- Throttling limits the execution of a function to once every specified time interval, no matter how many times the event fires.
- The function runs immediately and then waits for the interval before it can run again.
Example Use: Scroll event — only handle scroll every 200ms instead of on every pixel scroll.
✅ 3. Why Use Debouncing and Throttling? (Optimization)
- Both help optimize performance by reducing how often heavy or repeated functions run.
- Prevents unnecessary function calls that can cause lag or excessive network requests.
- Improves user experience and resource usage.
✅ 4. Practical Examples
Debouncing Example (Typing Search)
js
CopyEdit
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
const searchInput = document.getElementById('search');
searchInput.addEventListener('input', debounce(() => {
console.log('Searching for:', searchInput.value);
}, 500));
Throttling Example (Window Scroll)
js
CopyEdit
function throttle(func, limit) {
let lastFunc;
let lastRan;
return function(...args) {
if (!lastRan) {
func.apply(this, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(() => {
if ((Date.now() - lastRan) >= limit) {
func.apply(this, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
}
window.addEventListener('scroll', throttle(() => {
console.log('Scroll event handler called');
}, 200));
✅ 5. Key Differences
AspectDebouncingThrottling | ||
Function runs | After user stops triggering event | At regular intervals while events fire |
Use case | Typing, resizing, search input | Scrolling, mouse movement, resize |
Calls reduction | Runs once after events stop | Runs at fixed intervals during events |