Throttling and debouncing in Javascript

Throttling and Debouncing in JavaScript

In this article, we will learn about debouncing and throttling concepts. It’s a fundamental(basic concept) idea in web development interviews. In the first section, we will know the definition and usage. In a later section we will try to implement the concepts in Javascript.

Debouncing

Debouncing is a technique in which, no matter how many times the user fires the event, the event (attached function) will execute only after the specified time once the user stops performing the event.

We will try to understand these concepts by a simple example. Consider a small baby annoying her mother by asking about the chocolate often. But mother has told to that if you remain silent for 2 hours. That means you will get chocolate if you stay quiet for two hours. It means you will not get chocolate if you ask continuously. You will get new chocolate after two hours from your last request.

Throttling

Throttling is a technique in which, no matter how often the user performs the activity or executes the process, the desired function will run in a given time interval.

We will take a similar as discussed in the debouncing. Consider in your home your mom has created rasgulla for the guest. You, being loving rasgulla, keep on asking the item. Finally, she gives you a condition that you can have a rasgulla after a specific time limit(like one hour). In the meantime, you can ask for more rasgulla, but you will get it only after that period. Hopefully, I am able to describe the situation.

Difference between Debouncing and Throttling

DebouncingThrottling
Debouncing is a technique in which we can monitor the time delay of user action. Once the delay reaches a predefined time slot, we can make the second call.Throttling is a way to limit the number of execution of a function. It will perform a function, then drop all the calls of the function until a specific period.
We can use debounce in the search module. For example, we use the debouncing functionality in Amazon, Flipkart, or any e-commerce site.
Throttle can be used when the user clicks the button event. In that case, we can restrict the user by throttling the user event.
In the case of windows resize operations, we can use the throttling process. By using the process, we can reduce the number of execution.

When to use what?

In this section, we will discuss which functionality can be used in which specific scenario. Both concepts have their particular pros and cons based on their use cases.

Debouncing can be used if we are more concerned about the latest event that occurred. In the case of searching anything in the website search bar. In that scenario, debouncing will be preferred.

Throttling can be used when we are playing a game where shooting a gun is required. For example, we are trying to shoot up using a pistol with a specific firing gap. In the case of a machine gun, the throttle time will be different. We can say that pistol will fire five bullets in 10 seconds, and a machine gun will fire 100 bullets in 10 seconds. In this scenario, we can use throttling.

Implementing Throttling in Javascript

In the first part, we will try to implement a simple throttle function in javascript. It will be pseudo code.

// regular call to function handleAction
element.on('event', handleAction);

// throttle handleAction so it gets called only once every 2 seconds (2000 ms)
element.on('event', throttle(handleAction, 2000));

function handleAction(){
    console.log("Action is triggered");
}
const throttle = (fn, limit) => {
  let flag = true;
  return function(){
    let context = this;
    let args = arguments;
    if(flag){
      fn.apply(context, args);
      flag = false;
      setTimeout(() => {
        flag=true;
      }, limit);
    }
  }
}

In the simple event, whenever we click the button, the action is triggered. In the case of the throttle function, when users are acting(clicking) on the button. 

  1. In the first button click function will be executed. Because by default, the flag is true.
  2. While executing the action on the button, we changed the flag’s value from true to false.
  3. We have added the timeout, making it true at the specific delay time we have provided.
  4. When the flag becomes true, it will execute the function again.

In this way, the throttle will execute the function. It will decrease the number of execution of the function, and the website’s performance will improve.

Implementing Debouncing in Javascript

Please see the code below for debouncing functionality.

#html Part
<input type="text" onkeyup="betterDebounceFn()"/>

// Debouncing in Javascript
let count = 0;
const getAppData = () => {
  // calls an API and gets Data
  console.log("Fetching Data ..", count++);
}

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

const betterDebounceFn = debounce(getAppData , 300);
  1. In the first step, we have created a simple textbox in which we have attached an event on the onkeyup.
  2. We have created a simple function that is just doing a console log.
  3. While initiating the primary debounce function, it has two parameter functions to be executed and the delay we have provided.
  4. In that function, we are returning a new function in that also we have used the concept of closure.
  5. In that inner function, we have used the concept of setTimeout and clearTimeout. By utilizing these concepts, we are Scheduling our function to be triggered at a specific time.
  6. In this way, we are limiting the execution of the functions.

Debounce and Throttling implementations in libraries

In this article, we have tried to implement debounce and throttle functionality. But many libraries have implemented it. For example

Libray Example
Lodash (Debounce)_.debounce(saveInput, 300);
Lodash (Throttling)_.throttle(saveInput, 1000);

To conclude

We can conclude that throttling and debouncing can significantly improve the performance of our applications.