DEV Community

Cover image for Debouncing in Javascript
Vishal Gupta
Vishal Gupta

Posted on • Updated on

Debouncing in Javascript

Debouncing is a very good to have feature, when user is expected to do a particular action very very quickly, such as typing a product name for searching in an e-commerce site.

Imagine on each key press the client code makes and API call for fetching the suggestions to be shown in the search result, these are so many api calls, to avoid this situation of making so many api call we can implement debouncing.

Debounce Algo:

  1. Call a function on user action after a delay time
  2. Clear the previous delay time on the next action if the action is performed before that delay time
  3. Make use of setTimeout

Simple Code:

  <input id="debounce-input" />

// debounce logic
var timer = null;
const debounce = (actionHandler, delay) => {
  if (timer) {
    // clearing timer
    clearInterval(timer);
  }
  timer = setTimeout(actionHandler, delay);
};

// some costly function
const fetchDataFromAPI = () => {

  //here you can put your fetch logic

  console.log("fetchData");
};

// event binding to input
const elem = document.getElementById("debounce-input");
elem.addEventListener("input", e => {
  debounce(fetchDataFromAPI, 1000);
});

This is very simple implementation of Debounce just to give the idea that it can be achieved very easily.

One can use closures to move global variables inside the function

We should avoid including big libraries just for using small functionality like this

Top comments (1)

Collapse
 
dhilipkmr profile image
Dhilip kumar

Good one.
A couple of suggestions.
1.if(timer) check is unnecessary

  1. It does not maintain this context.You'll have to bind it to avoid unexpected results