debounce

Debouching example.

by joshiisaurabh

HTML

<h3>
Example with debouncing.
</h3>
<input type="text" onkeyup="searchProducts()"/> 
<h3>
Example without debouncing.
</h3>
<input type="text" onkeyup="getData()"/>

JavaScript

let counter = 0;
const getData = () => {
  // calls an API and gets Data
  console.log("Fetching Data ..", counter++);
}

const debounce = function (fn, d) { //Higher order function which returns another function.
  let timer;
  return function () { 
    let context = this,
      args = arguments;
    clearTimeout(timer);//This clears setTimeout 
    timer = setTimeout(() => {//call to getData() after 300ms 
      fn.apply(context, arguments);//fn.apply will getData()
    }, d);
  }
}

const searchProducts= debounce(getData, 300);//Debounce function.