Debouncing? What and How in Javascript.

Debouncing? What and How in Javascript.

·

2 min read

Learning Javascript and building tools/Apps in itself is a fun journey to embark upon, and while building these apps and websites we sometimes encounter some specific problems which causes performance issue that is where debouncing comes in. So, what does debounce mean? let's take an example of an e-commerce app where the user clicks the add to cart and you want to add only one product to the cart, right? but in the functionality without debounce a user will be able to add multiple items by constantly clicking on the "Add to Cart" button or sometimes a missed click adds the products to the cart and resulting in a bad UX experience. Some performance drops on the developer side are also caused by this.

In the above code when you can click on add to cart button an event is fired at every click, if you want to stop that we can use debounce function.

In the above code, we added a debounce function, It is basically a function that takes a function and a delay value as input and delays the function call by the specified delay time.

const debounce = (fn, delay ) => {
    return (...args) {
        setTimeout(() => {
              fn.apply(...args)
            }, delay)
}

So, How does it work? debounce take a function as an argument and returns an anonymous function with setTimeout to delay the future function calls which makes the component more performant and then this debounce can be used with anything you want to delay calling.

Where and how do you use debounce? do tell in the comments.