Site icon Primathon

What is Debouncing and Throttling?

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.

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.

Exit mobile version