5

Throttling VS Debouncing in Javascript

 3 years ago
source link: http://www.js-craft.io/blog/throttling-vs-debouncing-in-javascript/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Skip to content

Throttling VS Debouncing in Javascript

Some time 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
  • with debouncing we make sure a function is called just once, even if it was invoked 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:

I hope you have enjoyed this article and if you would like to get more articles about React and frontend development you can always sign up for my email list.

Newsletter subscribe:

Posts navigation

About your host

Hey there, thanks for dropping by! I’m Daniel, a software engineer with a big passion for Javascript and CSS. I stronlgy believe that education is the key to building a better, stable and richer world.
Twitter | RSS | Newsletter

daniel_js%20_craft.jpg

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK