Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

Debouncing and Throttling

Topic 7JavaScript Part 3 (DOM)

Debouncing and Throttling

Introduction

Debouncing and throttling are techniques used to optimize performance by controlling the rate at which functions are executed, especially for events that fire frequently.

Key Concepts and Definitions

Debouncing

Ensures that a function is executed only after a specified time has passed since it was last invoked. If the event occurs again within the wait time, the timer resets. Useful for scenarios where events occur rapidly, and we want to delay execution until the user stops triggering the event. Examples include searching in a text input field (to reduce API calls) and resizing a window.

Throttling

Ensures that a function is executed at most once in a specified time interval, no matter how many times the event occurs. Useful for limiting the frequency of function calls. Examples include handling scroll events (e.g., infinite scrolling) and resizing the browser window.

Step-by-Step Explanation

Differences Between Debouncing and Throttling:

Debouncing: Executes after a pause in events. Delays execution until the event stops firing. Use Case: Search inputs, window resize. Throttling: Executes at regular intervals during events. Limits the rate at which the function executes. Use Case: Scrolling, API rate limiting.

Examples

Debouncing Implementation:

function debounce(func, delay) {
  let timer;
  return function (...args) {
    clearTimeout(timer); // Clear the existing timer
    timer = setTimeout(() => func.apply(this, args), delay); // Set a new timer
  };
}

Example: Search Input:

const searchInput = document.getElementById('search');

const fetchData = (query) => {
  console.log(`Fetching data for: ${query}`);
};

const debouncedFetch = debounce(fetchData, 500); // Wait 500ms after user stops typing

searchInput.addEventListener('input', (event) => {
  debouncedFetch(event.target.value);
});

Throttling Implementation:

function throttle(func, limit) {
  let lastCall = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastCall >= limit) {
      lastCall = now;
      func.apply(this, args);
    }
  };
}

Example: Scroll Event:

const handleScroll = () => {
  console.log('Scroll event triggered');
};

const throttledScroll = throttle(handleScroll, 1000); // Execute at most once every 1000ms

window.addEventListener('scroll', throttledScroll);

Real-World Example: Debouncing Window Resize:

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

window.addEventListener('resize', logResize);

Real-World Example: Throttling Infinite Scroll:

const fetchMoreContent = throttle(() => {
  console.log('Fetching more content...');
}, 2000);

window.addEventListener('scroll', fetchMoreContent);

Summary

Debouncing ensures a function is executed only after a specified delay following the last event. Throttling ensures a function is executed at most once every specified interval. Debouncing is ideal for search input and window resize. Throttling is ideal for scroll events and API rate limiting.

Interview guide discussion

(0)

Join the discussion — login to comment and help other developers.

Login to comment