In this article, we will discuss and understand debouncing and throttling in javascript, which are very useful when it comes to the performance of a website.
Why to use ?
One word "performance".
Whenever we're attaching a performant-heavy function to an event listener, it's considered best practice to control how often the function is called. Debounce and Throttle are two methods for optimising the performance of scripts by controlling how often an event is called.
Let's understand both one by one:
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.
Example: Suppose you building an e-Commerce project and you have to implement a search feature there. When users types any keyword for a search, each keyword makes an API call.
Here is an example for the same ๐ Demo without debounce
In the above example when you type any keyword, that keyword runs an API call. This thing decreases the app performance as we are firing API for every search. We don't want this, what we want is, API should fire only when the user has stopped typing.
To fix this here comes debouncing into picture ๐
Demo with debounce ๐
Now here, we can see that search is making API calls only when the user has stopped timing. So, we are preventing unnecessary API calls. This will increase our project performance in a huge way. Wow !!
Here is the implementation of debounce function
function debounce(fn, delay){
let timer;
return function(){
clearTimeout(timer);
timer = setTimeout(()=> fn(), delay);
};
}
Suppose the delay is 1000ms which is equal to 1sec. So, here we initialized a timer and then returned a function. When the user types anything the function runs.
- first, we are clearing the timer if it's initialized already.
- Then we are running setTimeout function, which will run after the delay milliseconds.
- So, when a user types again, the previous initialized time will be clear out and new setTimeout timer will run again with new 1-second timing.
- If the user writes again, this process will be followed again. Thus we are preventing immediate API calls.
- When the user stops typing, then the function will run after 1 second. And then call API.
So, overall this is how this works in the background :)
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.
Example The below code renders a div with a scrollbar. We have added an event listener on the scroll event. Each time the user scrolls, an anonymous function is called that prints the number of times the scroll event is fired. When the user scrolls, we are running an API.
But, as this method is heavy, attaching it to a scroll event directly will cause it to fire frequently. This may cause an unnecessary load on the server. To prevent this, we have used the technique of throttling.
The example shows both API called without throttling and with throttling when you scroll. So, you can see clearly that to which extent throttling has improved performance.
Here is the implementation of throttling function:
function throttleFunction(func, delay){
let timerId;
if(timerId){
return;
}
timerId = setTimeout(()=> {
func();
timerId = undefined;
},delay)
}
Suppose the delay is 200millisecond.
- when first scroll event is fired,
throttleFunction
is called. - firstly,
timeId
isn't defined. So,if statement
will not execute. setTimeout
will run function after 200millisecond. Now timerId is defined.- When 2nd event for the scroll is fired,
timerId
isn't undefined.timeId
isn't undefined means setTimeout function has already been schedules. So, new timerId will not be generated. Therefore,if statement
will execute. and will return us out of the function. - This makes sure that before 200 milliseconds, we aren't able to make any API call. This makes sure that API calls will be called only once within the interval.
- When the scheduled interval is passed i.e. 200 milliseconds and the user is still scrolling, then our API call will run and schedule another API call for the future i.e. 200 milliseconds later.
Use of Debouncing and Throttling in Real Life
- We can throttle a button click event if we do not want the user to spam by clicking the button frequently.
- In infinite scrolling, we can use throttling as we want to load new content after some interval of scrolling, not at every scrolling event.
- With Mouse move event, if we are displaying the location coordinates of the mouse pointer, it is much better to show the coordinates once the user reached the desired location. Here, we can use debouncing
- In search feature we can use debouncing.
- etc.
Conclusion
In this article we understood the concept of debouncing and throttling in javascript along with real life examples. Code examples are also given to understand better.
Please write down in the comments what you liked or what you learned new things. I will appreciate your feedback on this.