DEV Community

Sashank Pindiproli
Sashank Pindiproli

Posted on • Updated on

Debouncing

Debouncing is the most common interview question that is asked when applying for a Front-End developer position.

Why is it the hot favorite question?
Most of the companies have a search bar feature that allows the user to search for the products.
And when the user searches for a particular product, for each keystroke it will call the rest API and get the results. This will cause a lot of performance issues as there will be a lot of API calls and also change the DOM structure on each response from the API call.
So how do we handle this performance issue? This is where debouncing comes into the picture.

What is debouncing?
In layman terms, "Wait until the function hasn't been called for some time period." This prevents multiple API calls, simple yet effective performance improvement for the website.


let counter = 0;

const incrementCounter = () => {
   console.log(`Counter increased by :${counter++}`);
}

const debounce = (fn, delay) => {
  let timer;
  return () => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn();
    }, delay);
  };
};

const debounceProductSearch = debounce(incrementCounter, 1000);
debounceProductSearch()

Top comments (2)

Collapse
 
thatonejakeb profile image
Jacob Baker

And as an added nicety you now know have an idea of how you would implement a software debounce for a mechanical button!

Collapse
 
sashycashy profile image
Sashank Pindiproli

I will implement that soon, but I would use the throttle for the button to cover the Throttle concept