Explain javascript debounce function?


A debounce function limits the rate at which a function can fire. For example, an autocomplete text bar that queries the server. If you query the server at each keystroke, it'll be unnecessarily have network and memory impact. What you can instead do is limit the number of these calls going in a given amount of time.

You can write your own debounce function that takes your actual function as an argument and executes it in a rate limited(throttled) way.

Example

const debounce = (cb, time) => {
   let timeout;
   return function() {
      const wrapperFunc = () => cb.apply(this, arguments);
      clearTimeout(timeout);
      timeout = setTimeout(wrapperFunc, time);
   }
}

This function takes 2 arguments callback and the interval in which it should be called. So let's say the first call to the API went at 1ms and you've set the time as 250ms, until 251ms, a new call wont be made to the API no matter how many times this function was called. You can replace your own function call using this call.

raja
Published on 19-Sep-2019 07:55:55
Advertisements