Debouncing and Throttling in JavaScript

Debouncing and Throttling in JavaScript

What are they and how do we use them to implement optimization in our web applications?

ยท

5 min read

Hello readers! In this blog we shall discuss as to what is Debouncing in Javascript and how can we use it in our projects. Debouncing is a very vital concept in Javascript for interviews as well. So stay tuned!

Debouncing in Javascript is an optimisation method to avoid unnecessary external API calls and provide a smoother User Experience by minimising the number of network calls.

Throttling is a similar method which uses rate limiting for a fixed time interval unlike debouncing which is dynamic to the set delay time.

Debouncing in action

Let us begin by taking an example in the real world project scenarios. When we go to any e-commerce site and we search for a product in the search bar, the site auto suggests us items to look into. On the hind side, the browser fires many network calls to search for products which fit the search query the user has typed in the search bar.

Screenshot (197).png

Let us go through the code of the simpler implementation of this search items scenario.

//React Component
 export default function Debounce() {
  function fetchData(e){
    console.log("fetching data..",e.target.value);
  }
  function debounce(cb, delay) {
    let timer;
    return function (...args) {
      if (timer) clearTimeout(timer);

      timer = setTimeout(() => {
        cb(...args);
      }, delay);
    };
  }
  const handleDebounce = debounce((e) => {
    fetchData(e);

  }, 1000);
  return <input onChange={handleDebounce} />;
}

So before deep diving into the code, let us understand the working principle of debouncing in our scenario of usage. For example, a user enters a search query into the search bar "school" , the browser by default fires network calls on every change in the query which is very expensive in the application lifecycle. To minimize these additional calls , our debounce function comes into play.

The main motive of debounce function here is to ensure if and only if there is a time interval of x milliseconds (delay) between two changes on the search query and only then to fire a network call. This shall ensure that the browser is not calling for data more than necessary at a given point.

Now moving on to the code snippet, debounce function expects a callback function and an assigned time delay in milliseconds. It sets a timer according to the given delay post which a call is made and the fetchData function is called . In case there is another change in the query, the previously assigned timer is cleared and timer starts over for x milliseconds again instead of making repetitive calls for every change and finally when there is no subsequent change for the x milliseconds, data is fetched and changes are accordingly reflected on the UI.

Throttling in action

Let us take the same scenario as of a ecommerce store but instead of a search bar, let us use a button maybe a "Place Order" button which fetches data post your order is placed. As we know that throttling works on the principle of a constant rate limiting since the first call, so unless the time interval has not passed, the button shall behave as disabled no matter how many times you over-click it. Once the timer of x milliseconds since the first call has passed, you can click the button again to access the desired functionality of the button.

Now how shall we go about coding this concept for usage?

//React Component
export default function Throttle() {
  function fetchThrottlingData() {
    console.log("Fetching data.. throttling");
  }
  function throttle(func, limit) {
    let flag = true;
    return function () {
      if (flag) {
        func();
        flag = false;
        setTimeout(() => {
          flag = true;
        }, limit);
      }
    };
  }
  const handleThrottle = throttle(() => {
    fetchThrottlingData();
  }, 1000);
  return <button onClick={handleThrottle}>click me</button>;
}

Screenshot (198).png

So as we see above, the limit assigned is 1000 milliseconds or 1 second so even if you press the button 3 times in a second it shall work only once because 2 out of those 3 times the button was rate limited. This must give you a clear example of how throttling works to limit the number of network calls based on a constant time interval.

Debouncing vs Throttling

debvstrottl.png

So now that we have seen live examples of these concepts to limit expensive calls in our application, which do you think is the better approach? To me, it all depends on the use case like the search query debouncing makes sense that whenever the user has completed his query and there is sufficient gap between two keystrokes, only then issue a fetchData call. Throttling here would make less sense to me because I would not like to fire calls in between when the user is still typing a search query also if the query is too short the user might have to wait for a longer interval upon finishing the query.

Moving to our second scenario of a button click, throttling makes more sense because I do not want a kid or somebody's cat running on their keyboard to break my application and fire calls based on the user activity. Instead, throttling allows me to limit this fetchData behavior of my application independent of the user activity and disable the button's functionality to avoid any miss-clicks or over clicks that shall fire expensive API calls from the browser.

Conclusion

So on a concluding note, I would say that both these concepts are very important and vital to the web developer industry and can be seen in action in various daily use cases.

Use cases for debouncing:

  • Searching on a website
  • Resizing a window
  • Saving in an autoSave feature

Use case for throttling:

  • Click of a button to avoid spamming
  • issuing data from API calls to avoid over usage of server transaction capacity

Throttling makes decision based on the last function call made and debouncing makes a decision based on the user activity like time interval between two keystrokes.

Hope you guys enjoyed this blog and understood my take on these concepts.

Thankyou for reading!

ย