Hello and welcome to my blog. Today, we are going to write a debounce function from scratch and I will explain the code line by line.
Debouncing is a technique used to optimize asynchronous operations, such as fetch calls to APIs and scroll events. In simple terms, debouncing delays the processing of an event.
The following code demonstrates an input element without debouncing:
For every user input (keyup/keydown) event, the event listener (“onClick”) calls the event handler function (in our case, the handleChange function). For a small application, this won’t cause any performance delays, but for large data websites like Flipkart and Meesho, the repeated function call can cause performance delays.
To optimize the input element, we can implement the following changes:
We are going to build the debounce function step by step. The first step is to delay the function call. To do this, we can use the timer function. However, we need to make a function call after some delay, which is where the setTimeout function comes in.
Here is the code implementation following the above steps:
const debounce = (cb, wait) => {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
cb(...args);
}, wait);
};
};
Here is a breakdown of what each line does:
Here is an example of what the input element looks like with debouncing:
We can see that there is a slight delay. we achieved the goal
That brings an end to this blog. Thanks for reading and happy coding!