DEV Community

Cover image for Debouncing vs Throttling
revanthrev23
revanthrev23

Posted on

Debouncing vs Throttling

Let us consider an example where we are trying to build a search bar, which has the capability of auto-complete. Now it gets this data that is suggested via an api. Hence it has to make an api call over the internet. Now autocomplete works with each and every character the user enters. But if our api was to be called each and every time when the user types something, it would be an overhead on our webapp, and it would decrease the performance as we have to handle so many network calls.

Debouncing and throttling could be made use of to improve our performance.

Debouncing

Debouncing is a technique used to ensure that time-consuming tasks are not called so often, that it negatively impacts the performance of the web page. In other words, it limits the rate at which a function gets invoked.

If we implement debouncing, we can fire an api call only when there is a pause of a certain amount of time between two consecutive keystrokes from the user. In other words, if the user pauses for a certain amount of time, before typing again, we fire an api call in that gap. Here we set a sensible time limit like maybe 500ms or 1s.

We can make use of setTimeout to implement debouncing:

const getData = () => {
    console.log(“Assume this is the API call”);
}
const debouncing = function(fn,d) {
    Let timer;
    return function(){
        let context = this;
        args = arguments;
        clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(context,arguments);
        }, d);
    }
}
debouncing(getData, 300);
Enter fullscreen mode Exit fullscreen mode

Throttling

Throttling is a technique in which, no matter how many times the user fires the event, the attached function will be executed only once in a given time interval. Or in other words, we trigger an event only on the first input made by the user.

Hence debouncing is more suitable on button clicks which perform a critical action like paying bills, or even on window resizing, etc.

If we use throttling in our example above, we can simulate it in such a way that the api would be fired after the user has typed everything.

This is how we can implement throttling:

   function throttleFunction(func, delay) {
     return function (args) {
     let previousCall = this.lastCall;
     this.lastCall = Date.now();
     if (previousCall === undefined || 
          (this.lastCall - previousCall) > delay) {
       func(args);
      }
    }
   }
   const getData = () => {
    console.log(“Assume this is the API call”);
   }
   throttleFunction(getData, 300);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Some comments have been hidden by the post's author - find out more