Debouncing vs. Throttling in JavaScript: A Complete Guide with Interview Questions

Performance optimization is crucial in JavaScript applications, especially when handling frequent user interactions like scrolling, resizing, or keypress events. Two powerful techniques used to limit function execution frequency are debouncing and throttling.

In this blog, we’ll explain what debouncing and throttling are, provide detailed coding examples, and cover interview questions with answers related to these concepts.


What is Debouncing in JavaScript?

Debouncing is a technique that ensures a function is executed only after a specified delay following the last event trigger. It is useful for situations where multiple rapid event triggers should result in a single function execution after a delay.

Common Use Cases of Debouncing

  • Search box auto-suggestions (trigger API call after user stops typing)
  • Resize event handlers (execute code after user stops resizing window)
  • Button click prevention (prevent multiple clicks from submitting a form multiple times)

Example: Implementing Debouncing

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

// Example usage
function searchQuery(query) {
    console.log("Fetching results for:", query);
}

const debouncedSearch = debounce(searchQuery, 300);

// Simulating user typing in a search box
debouncedSearch("Ja");
debouncedSearch("Jav");
debouncedSearch("Java"); // Only "Java" triggers the searchQuery function after 300ms

How It Works

  • Every time debouncedSearch is called, the previous timer is cleared.
  • Only the final call (after delay) executes the searchQuery function.

What is Throttling in JavaScript?

Throttling ensures that a function is executed at most once within a specified time interval, even if triggered multiple times.

Common Use Cases of Throttling

  • Scroll event handling (trigger an action once per interval during scrolling)
  • API polling (limit API requests at regular intervals)
  • Button click handling (prevent multiple rapid clicks from triggering multiple submissions)

Example: Implementing Throttling

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

// Example usage
function onScroll() {
    console.log("Scrolling event triggered:", Date.now());
}

const throttledScroll = throttle(onScroll, 1000);

// Simulating multiple scroll events
window.addEventListener("scroll", throttledScroll);

How It Works

  • The function executes immediately when first called.
  • After that, it executes only once per specified interval (1s in this case).

Debouncing vs. Throttling: Key Differences

FeatureDebouncingThrottling
Execution TimeDelays execution until after event stopsExecutes at fixed intervals
Best Use CasesSearch input, resizing eventsScrolling, button clicks, API polling
Number of Executions1 (after delay)Multiple (at regular intervals)

Interview Questions on Debouncing and Throttling

1. What is the difference between debouncing and throttling?

Answer:

  • Debouncing postpones function execution until after a specified delay following the last event trigger.
  • Throttling executes a function at most once per interval, even if the event keeps triggering.

2. When would you use debouncing over throttling?

Answer:
Use debouncing when you want to ensure execution happens only after the event has stopped firing. Example: search input auto-suggestions.


3. How would you implement a debounce function in JavaScript?

Answer:
The following function delays execution until after the event stops occurring for the specified time.

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

4. How would you implement a throttle function in JavaScript?

Answer:
The following function ensures that execution happens at most once in the given time frame.

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

5. Can you use both debouncing and throttling together?

Answer:
Yes! You can apply debouncing inside throttling to ensure that an event fires at regular intervals while also handling spikes in event triggers efficiently.


Final Thoughts

  • Debouncing is best when you want to delay execution until the event has stopped firing (e.g., search input).
  • Throttling is best when you want execution to happen at fixed intervals (e.g., scrolling events).
  • Both techniques help optimize performance and reduce unnecessary function calls.

Additional Essential JavaScript Interview Questions on Various Topics

React Js Interview questions:

Top Javascript Books to Read

Leave a Comment