Others

What is Debouncing and Throttling?

May 9, 2023

Before reading this I would recommend you to have an absolute clarity of closures.

Why to Debounce or throttle?

Imagine you have implemented a scrollbar listener and at each scroll you are doing some work. But this will cause performance issue because when you scroll for let’s say 10px the function will be called at each scroll, this will create a tremendous work for the browser and hence the user experience will not be up to the par.

Scroll Listener

Now imagine, you are doing some API calls in scrollbarCallback(), in that case you will be firing your API even on a slight scroll. This is huge setback when it comes to performance. To solve this Debouncing and Throttling comes in for rescue.

What is Debouncing?

In the debouncing technique, no matter how many times the user fires the event, the attached function will be executed only after the specified time once the user stops firing the event.

How to implement Debouncing?

Custom Debouncer Function

Now let’s break this down.

  • debouncedScrollbarCallback function is going to store the debounced function.
  • setTimeout is a function which will hold the function firing for a given time. It also returns a timerId which is a positive integer, which will be later used to terminate the previous established setTimeout.
  • The purpose of defining timer variable is to bind the variables of debouncer function with the return function i.e. to form a closure. This will store the ID of last created setTimeout function.
  • In this example, we are having a delay of 300ms if the user scroll before the 300ms the last timer will get terminated and new timer will start.

What is 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.

How to implement Throttling?

Simple throttle function

Conclusion

The main difference between throttling and debouncing is that throttling executes the function at a regular interval, while debouncing executes the function only after some cool-down.

The most useful application of debouncing is used in search bar, same as used in Google, amazon, flipkart and many more or where user is performing an action very often. In real life you will be mostly using a library to implement this, you can checkout lodash, it provides a great support for debounce function which can be used to create debounce function.

Leave a Reply

Your email address will not be published. Required fields are marked *