0
0
JavascriptComparisonBeginner · 4 min read

Debounce vs Throttle in JavaScript: Key Differences and Usage

In JavaScript, debounce delays a function call until a specified time has passed without new events, while throttle limits a function to run at most once every set interval. Both control how often a function runs during rapid events but serve different purposes.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of debounce and throttle to understand their main differences.

FactorDebounceThrottle
PurposeDelays execution until events stopLimits execution to fixed intervals
Function CallsRuns once after last eventRuns at regular intervals during events
Use CaseSearch input, resize eventsScroll, mouse move events
BehaviorIgnores intermediate callsExecutes periodically
Example DelayWaits 300ms after last eventRuns once every 300ms
⚖️

Key Differences

Debounce waits until a burst of events ends before running the function once. It resets the timer every time a new event happens, so the function only runs after no events occur for the set delay. This is useful when you want to react only after the user stops typing or resizing.

Throttle, on the other hand, runs the function at most once every fixed time interval, no matter how many events happen. It ensures the function runs regularly during continuous events but not too often. This is helpful for things like tracking scroll position or mouse movement without overwhelming the browser.

In short, debounce groups rapid events into one final call after inactivity, while throttle spaces out calls evenly during activity.

⚖️

Code Comparison

Here is a simple example of debounce in JavaScript that logs a message only after the user stops resizing the window for 500 milliseconds.

javascript
function debounce(func, delay) {
  let timerId;
  return function(...args) {
    clearTimeout(timerId);
    timerId = setTimeout(() => func.apply(this, args), delay);
  };
}

const logResize = debounce(() => {
  console.log('Window resized');
}, 500);

window.addEventListener('resize', logResize);
Output
Logs 'Window resized' once after resizing stops for 500ms
↔️

Throttle Equivalent

This example shows throttle that logs a message at most once every 500 milliseconds while the user resizes the window.

javascript
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));
    }
  };
}

const logResizeThrottle = throttle(() => {
  console.log('Window resized');
}, 500);

window.addEventListener('resize', logResizeThrottle);
Output
Logs 'Window resized' repeatedly at most once every 500ms during resizing
🎯

When to Use Which

Choose debounce when you want to wait for a pause in events before running your function, such as validating input after typing or resizing a window.

Choose throttle when you want to run a function regularly at fixed intervals during continuous events, like updating scroll position or tracking mouse movement.

Use debounce to reduce unnecessary calls after rapid events stop, and throttle to limit calls during ongoing events.

Key Takeaways

Debounce delays function execution until events stop firing for a set time.
Throttle limits function execution to once every fixed interval during events.
Use debounce for actions after user stops input or resizing.
Use throttle for regular updates during continuous events like scrolling.
Both improve performance by controlling how often functions run on rapid events.