Debouncing in Java Script

Debouncing is a technique of performance optimization which relies on concept of calling a function after user stop his/her activity for certain amount of time.

Suppose we have a web application which has a button to fetch records from database. It is very common that user click the button multiple times by mistake or for fun. Are you going to make API call on every click? Definitely not because database call is expensive operation. This is where debouncing comes into picture. Suppose our HTML file is something like this.

Now if we simply call backend we will send n number of request for fetching the data which definitely very bad for performance.

To overcome this problem we can make api call after certain period of time but again n number of setTimeout will be registered. For that purpose we have to clear the previous timeout. So we have to go as below code.

function debounce(fn, delay) {

let setTimeoutId;

const that = this;

return function () {

let args = arguments;

let context = this;

clearTimeout(setTimeoutId);

setTimeoutId = setTimeout(function () {

fn.apply(context, args);

}, delay);

};

}

function sum(a, b) {

console.log(“making some api call”);

console.log(a + b);

}

const apiCall = debounce(sum, 2000);

As we are calling apiCall function which will return another function will be bounded to button.

Note: Debounce function will be called one and hence setTimeoutId value will be initialized once and due to closure property inner function will be able to access setTimeoutId and its previous value.