Categories
interview

Debounce (ES6)

Sometimes, we would like to wait a certain minimum time period before successive method calls. For example in events like onscroll(), onresize(), this can go a long way in terms of optimizing the page performance as a whole.

The wrapping of the methods using a Debounce method is a simple way to achieve the desired result.

const debounce = (fn, interval) => {
  let timeout;
  return (...rest) => {
    if (timeout)
      clearTimeout(timeout);
      timeout = setTimeout(() => {
        fn.apply(this, rest);
      }, interval);
  };
}

const test = (inp) => {
  console.log(inp);
};

const db = debounce(test, 1000);
const cb = () => {
  db('test');
};
const button = document.createElement('button');
button.innerHTML = 'fire';
document.body.appendChild(button);
button.addEventListener('click', cb);

Demo