JavaScript Debouncing and Throttling

JavaScript Debouncing and Throttling are two techniques used to improve performance and enhance user experience while using DOM Events. Both are similar, but different in execution. Debouncing delays the execution until a certain time has passed from the last call. Throttling limits the rate at which the function can be called.

Debouncing: Executes the function after a specified delay once the event has stopped firing.

Throttling: Executes the function at regular intervals while the event is continuously firing.

The example below is using DOM Click event, one without delay and one with delay.

Without delay

0

With delay

0

Scrolling Issue

While using the window scroll event, the scrollTop value is not always the next expected value. The reason is the refresh rate. An average laptop has a 60Hz screen, which means it cannot refresh more than 60 times in a second.

60Hz is equal to 1/60 * 1000 milliseconds, i.e 16.66 milliseconds.

Even if laptop has better refresh rate like 90 or 120 Hz, the browser engine is not capable to utilize it because of JS engine and Operating System restriction.



0

Twitter Scrolling Issue

Twitter faced such an issue in 2011. When scrolling fast, the UI froze because the number of posts fetching from the server using AJAX was excessive. At that time, fetch was not invented. They added a delay of 250ms between two functions to resolve this issue.

That is why we need to understand both debouncing and throttling in depth.


Debouncing

Debouncing is a technique used to limit the rate at which a function is executed. It ensures that the function is only called after a certain amount of time has passed since the last time it was called. This is particularly useful for events that fire rapidly, such as window resizing or keypress.

Without Debouncing

With Debouncing

Debouncing Example

In the example below, the function will only execute after the user has stopped resizing the window for 500 milliseconds.


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

const x=document.querySelector('input');

x.addEventListener('input', debounce(function() {
    console.log(x.value);
}, 500));

Using JS ES6+


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

const x=document.querySelector('input');

x.addEventListener('input', debounce(function() {
    console.log(x.value);
}, 500));

Throttling

Throttling is a technique used to limit the rate at which a function is executed. It ensures that the function is only called at most once in a specified period of time. This is particularly useful for events that fire rapidly, such as window resizing or scrolling.

Throttling Example

In the example below, the function will only execute once every 500 milliseconds, regardless of how many times the user resizes the window.


    function throttle(myFunc, delay) {
    let timerFlag = null; 
      
    return (...args) => {
    if (timerFlag === null) { 
        myFunc(...args); 
        timerFlag = setTimeout(() => { 
            timerFlag = null; 
        }, delay);
        }
    };
    }

    window.addEventListener('resize', throttle(function(e) {
        console.log('Resized');
    }, 500));

Debounce vs Throttle: Comparison Table

Feature Debouncing Throttling
Definition Executes function after a specified delay since the last event. Executes function at regular intervals while event is firing.
Use Case Search input, window resize, auto-save. Scroll events, API rate limiting, continuous user actions.
Example Waits for user to stop typing before firing search. Fires scroll position update every 100ms while scrolling.
Frequency Only once after the last event. At most once per interval.
Delay Reset Yes, resets on every event. No, runs at fixed intervals.

Frequently Asked Questions (FAQ)

What is debouncing in JavaScript?

Debouncing is a technique to ensure a function is only executed after a certain period has passed since the last time it was invoked. It is useful for events like search input, window resizing, or auto-saving.

What is throttling in JavaScript?

Throttling is a technique to ensure a function is only executed at most once in a specified interval, regardless of how many times the event is triggered. It is useful for scroll events, API rate limiting, and continuous user actions.

When should I use debouncing vs throttling?

Use debouncing when you want to execute a function only after the user has stopped triggering the event (e.g., after typing stops). Use throttling when you want to execute a function at regular intervals while the event is being triggered (e.g., while scrolling).

Can I use both debouncing and throttling together?

Yes, you can combine both techniques if your use case requires limiting both the frequency and the timing of function execution.

Are there libraries for debouncing and throttling?

Yes, popular libraries like Lodash provide _.debounce and _.throttle utility functions for these patterns.


Summary

Debouncing and throttling are essential techniques for optimizing event-driven JavaScript applications. Use them to improve performance, reduce unnecessary function calls, and enhance user experience.