Member-only story

Debouncing in JavaScript

Santosh yadav
2 min readMar 10, 2021

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

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

If we simply call backend, we will send n requests to fetch the data, which is clearly very bad for performance.

To overcome this problem, we can make an API call after a certain period of time, but again n numbers 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);

--

--

Santosh yadav
Santosh yadav

No responses yet