🟨 JavaScript Q18 / 121

What is debouncing and throttling?

AI-Powered Answer ✓ Answered

Debouncing and throttling are two distinct performance optimization techniques used in JavaScript to control how often a function is executed, particularly in response to events that fire rapidly (e.g., window resizing, scrolling, typing in a search bar, mouse movements). They help prevent excessive function calls, improving application responsiveness and efficiency.

Debouncing

Debouncing is a technique that limits the rate at which a function can fire. When you debounce a function, it will only execute after a specified amount of time has passed since its last invocation. If the debounced function is called again within that timeout period, the timer is reset. This ensures that the function only runs once after a series of rapid events has completely stopped.

Common use cases for debouncing include:

  • Search input fields: Only make an API call for suggestions after the user has stopped typing for a short period.
  • Window resizing: Only perform layout recalculations once the user has finished resizing the window.
  • Save buttons: Trigger a save operation only after a user pauses their input.
javascript
function debounce(func, delay) {
  let timeoutId;
  return function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}

// Example usage:
const searchInput = document.getElementById('search');
searchInput.addEventListener('input', debounce((event) => {
  console.log('Fetching data for:', event.target.value);
}, 500));

Throttling

Throttling is a technique that limits the execution of a function to a maximum of once within a specified time period. Unlike debouncing, throttling guarantees that the function will execute regularly at fixed intervals while events are continuously firing. It ensures that a function doesn't execute more frequently than a predefined rate.

Common use cases for throttling include:

  • Scroll events: Update UI elements (e.g., sticky headers, lazy loading) at a controlled rate, rather than on every pixel scroll.
  • Mouse move events: Track cursor position for complex animations or drag-and-drop interfaces without overwhelming the browser.
  • Button clicks: Prevent accidental multiple submissions by only allowing a click every X milliseconds.
javascript
function throttle(func, delay) {
  let inThrottle, lastFn, lastTime;
  return function(...args) {
    const context = this;
    if (!inThrottle) {
      func.apply(context, args);
      lastTime = Date.now();
      inThrottle = true;
    } else {
      clearTimeout(lastFn);
      lastFn = setTimeout(function() {
        if (Date.now() - lastTime >= delay) {
          func.apply(context, args);
          lastTime = Date.now();
        }
      }, Math.max(delay - (Date.now() - lastTime), 0));
    }
  };
}

// Example usage:
const scrollContainer = document.getElementById('scroll-container');
scrollContainer.addEventListener('scroll', throttle(() => {
  console.log('Scroll event handled!');
}, 200));

Key Differences

FeatureDebouncingThrottling
Execution LogicExecutes function only after a pause in events (resets timer).Executes function at most once within a given time period (rate limiting).
TimingFunction runs at the 'end' of a series of events.Function runs at regular 'intervals' during a series of events.
Number of CallsEnsures only one call per 'event burst'.Ensures a limited number of calls over time (e.g., 5 calls per second).
When to useWhen you only care about the final state after events stop (e.g., search input, window resize end).When you need to perform an action regularly while events are happening (e.g., scroll tracking, game updates).