Checkout my Getting Started with React video course on Skillshare. It is 100% free.

Throttling VS Debouncing in Javascript

A few days ago I've written a short article about debouncing in Javascript.

Another term very related to debouncing is throttling. Both techniques do the same thing: they make sure expensive operations (like API calls) are limited in a time interval.

But, in different ways:

  • throttling makes sure that one function is not called more than once in X milliseconds
  • meanwhile debouncing makes sure that a function is executed only if it was not called again for the past X milliseconds; basically with debouncing we make sure a function is called only once, even if it was involved multiple times.

A simple implementation for a throttling function may look like this:

function throttle(f, t) {
    return function (args) {
         let previousCall = this.lastCall;
        this.lastCall = Date.now();
            if (previousCall === undefined || (this.lastCall - previousCall) > t) { 
                f(args);
            }
     }
}

You can see in the other tutorial the implementation for the debouncing function.

For example, if we have a user is pressing a button every 500 milliseconds for 6 seconds:

  • with a throttling interval of 2 seconds, the call for the button will take place 3 times.
  • with a debouncing time of 500 milliseconds, then after 6 seconds, the call for the button only takes place just once

Also if you want to read more I have found useful the following links: