JavaScript Tutorial in Hindi #34 | Debouncing vs Throttling in JS (2025)

✅ 1. What is Debouncing?

  1. Debouncing delays the execution of a function until a certain time has passed after the last event.
  2. If the event keeps firing, the function won’t run until the events stop for that delay time.
  3. 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?

  1. Throttling limits the execution of a function to once every specified time interval, no matter how many times the event fires.
  2. 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)

  1. Both help optimize performance by reducing how often heavy or repeated functions run.
  2. Prevents unnecessary function calls that can cause lag or excessive network requests.
  3. 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 runsAfter user stops triggering eventAt regular intervals while events fire
Use caseTyping, resizing, search inputScrolling, mouse movement, resize
Calls reductionRuns once after events stopRuns at fixed intervals during events