This content originally appeared on DEV Community and was authored by Abhishek Jain
Debouncing is a pattern that allows delaying execution of some piece of code until a specified time to avoid unnecessary CPU cycles, API calls and improve performance.
Why debouncing?
One word "Performance".
Suppose, you are building an e-commerce application. There you have to implement a search bar for searching products And when the user types in a character, an API call is made.
Look at the example below.
In the above example, we're having a simple searchBar and a count of API calls made. As we type in the searchBar, the count of API called increases with each character. But that's not what we want to happen. What we want is to wait for the user to stop typing. As soon as the user stops typing then we want to make the API call.
so, how can we fix this? - here comes debouncing into play.
Final version with debouncing.
Pretty cool huh?
The debouncing function
Take a look at this debounce function we implemented above.
function debounce(fn, delay) {
let timer;
return function () {
clearTimeout(timer);
timer = setTimeout(() => fn(), delay);
};
}
What we are doing here is, initialize a timer then return a function
. As soon as the user starts typing the function
executes -:
First it clears the timer if it's initialized.
then it assigns the timer setTimeout function, which will run after 1 second if it is not cleared.
if the user types any character within 1 second the
function
will be called again. But in the above step, we already assigned the setTimeout function to the timer variable. So the clearTimeout will clear the function from the timer variable and also assign a new setTimeout function to the timer variable.if the user didn't type and 1 second has passed, the function in setTimeout will execute and make the API call.
That's it.
The full version of the debounce function with this
and argument binding is -:
function debounce(fn, delay) {
let timer;
return function () {
const context = this;
const args = arguments;
clearTimeout(timer);
timer = setTimeout(() => fn.apply(context, args), delay);
};
}
Well, this is it from my side. See you soon ?
This content originally appeared on DEV Community and was authored by Abhishek Jain

Abhishek Jain | Sciencx (2021-02-16T15:05:49+00:00) Debouncing in Javascript.. Retrieved from https://www.scien.cx/2021/02/16/debouncing-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.