Debouncing and Throttling in javascript

What are debouncing and throttling and how to implement them?

Introduction

Debouncing and throttling are often confused by the developers. Both are two different techniques of doing a similar task - controlling the number of times a function should be executed over time. Debouncing and throttling help us to optimize event handling.

Events

An event is an action that is performed by the user, for example when clicking on a button that is an onClick event, changing the input text value that is an onChange event. If we have a button and we want to send an API request when the button is clicked then we handle that event in the following way as shown in the code-

const button = document.querySelected(".button");

button.addEventListener("click", ()=>{
      fetchData();    
});

If we click on that button multiple times then the API request is sent multiple times, in this case, we need to optimize this event and we use debouncing and throttling. But how to decide what to use? For that, we need to first understand throttling and debouncing individually.

Throttling

A throttled function is called once per N amount of time. If it is called again within that time, then it is ignored. Let's take an example of a scroll event on DOM without throttling

The callback function is called a numerous amount of time and we don't need that. It reduces the performance of our website. To tackle this problem we use a throttled function that runs only once per N amount of time.

Implementing Throttle

function throttle(func, duration) {
        let wait = false;
        return function (...arguments) {
          if (!wait) {
            func.apply(this, arguments);
            wait = true;
            setTimeout(() => {
              wait = false;
            }, duration);
          }
        };
      }

After throttling the callback function of the scroll event, the output is:

Debouncing

A debounced function is called after a particular amount of time has passed since its last call. For example- when we search for something on google the suggestions are shown after a few milliseconds and not immediately as we type, this is due to debouncing. It sends the API request only after the user has stopped typing. Let's take the example of the search bar.

An API request is sent on every keystroke, this sends unnecessary API requests. We need the user to first complete typing and then make the request. To achieve this we use debouncing.

Implementing debouncing

function debounce(func, timeout = 300) {
        let timer;
        return (...args) => {
          if (timer) clearTimeout(timer);

          timer = setTimeout(() => {
            func.apply(this, args);
          }, timeout);
        };
      }

Now the event is triggered on every keystroke but the request is sent only after 500 milliseconds after the last keystroke. This helps us to avoid unnecessary requests.

Conclusion

Debouncing and throttling both help us to ignore extra unnecessary event triggers. Debouncing is used when we want to perform something after the user has stopped triggering the event. It can be used in search bars or window resizing. Throttling is used when we want the function to execute once in a particular time period. It can be used for scroll events. Now we have understood the working and implementation of both debouncing and throttling. As for the question we had in the beginning about what to use for the button click event, I want to you figure out the answer.