Reusable Debounce Function

Debouncing a function gives us a way to wait for input to stop and only then trigger a set of actions. This is particularly useful when we have to call a function only when user input is complete (or there is a gap in typing that we can utilise for processing).

Debounce avoids sending multiple requests that load the client as well as server with needless processing. We have previously seen how debounce can be done using a simple timeout.

We will level that up with more reusable code.

Using underscore.js

Underscore.js gives us a bunch of really useful functions. You can keep your code simple by just leveraging the power of debounce utility in underscore.

let locWeather = _.debounce(getWeatherForLocation, 600);
// ...

The above code will trigger logic to get weather 600ms after user has stopped typing in the location.

The custom way

You can also do debounce using a custom function. This is preferable if you are looking at really lean bundle sizes and do not use other utilities provided by underscore.js.

The following HTML provides writes a message every second to denote when the function is called. The function is called only once per second no matter how many times the button is clicked.

    <button id="debounce">
      Fetch weather
    <p id="weather"></p>
      var button = document.getElementById("debounce");
      var callNum = 0;
      const debounce = (func, delay) => {
        let debounceTimer;
        return function() {
          console.log("debouncing weather call..");
          const context = this;
          const args = arguments;
          debounceTimer = setTimeout(() => func.apply(context, args), delay);
        debounce(function() {
          callNum += 1;
          ).innerHTML += `<br>Weather fetched.. ${callNum}`;
        }, 1000)

See it in action -


comments powered by Disqus