DEV Community

Cover image for Debouncing in the Javascript
Keval Rakholiya
Keval Rakholiya

Posted on

Debouncing in the Javascript

Introduction

In this post, I'll explain how to achieve denounce of the actions in javascript. We will use a timer and callback functions.

Prerequisite

Why Does it Matter?

Improving speed and performance is a big challenge these days. Users are getting more modern and everyone wants to be done their tasks quickly. To improve the speed of the web pages we are optimizing the javascript of the web. Here is one more solution to improve the performance of the web page by implementing the debounce on the events.

What the hack is Debounce?

In computer engineering, the Debounce is a pattern or a programming approach where the program collects similar events from the inputs and reacts to only the last event in a given period of time. By this, the program doesn't need to react for every event and because of this it may save memory and improve CPU efficiency.

Let's understand the problem!

Let's assume, we have a function called runme that makes an API call and calculates a ton of data in the backend. We have a button that triggers the runme function on the click event. Now if the user clicks three times on the button back to back the runme will call and execute three times which is unnecessary. To overcome this problem we use Debouncer.

Now we will solve the above problem with the example. It's time to walk through the example for better understanding, Let's GOOO...

const debouncer = (fn, time) => {
    let timer;
    return function (...args) {
        clearTimeout(timer);
        timer = setTimeout(fn.bind({}, ...args), time);
    };
};
Enter fullscreen mode Exit fullscreen mode

The above function takes two arguments, the first one is the function of which we want to make a bouncer function and the second argument is the delay time in ms. And the function returns a new function that will execute after a certain time period.

// Runme without Debounce
function runme(temp) {
    console.log(temp);
}
replicaOfRunme(1);
replicaOfRunme(2);
replicaOfRunme(3);
/**
 * O/P: 1 2 3
 */

// Runme with Debounce
let replicaOfRunme = debouncer(runme, 2000);
replicaOfRunme(1);
replicaOfRunme(2);
replicaOfRunme(3);
/**
 * O/P: 1
 */
Enter fullscreen mode Exit fullscreen mode

I hope this will help and fulfill your requirements for all the developers who want to add Debounce to events. Suggestions are most Welcome. Reach me at Github.


Top comments (0)