This page looks best with JavaScript enabled

Reusable Debounce Function

 ·   ·  ☕ 2 min read

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.

1
2
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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<html>
  <body>
    <button id="debounce">
      Fetch weather
    </button>
    <p id="weather"></p>
    <script>
      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;
          clearTimeout(debounceTimer);
          debounceTimer = setTimeout(() => func.apply(context, args), delay);
          console.log("..done");
        };
      };
      button.addEventListener(
        "click",
        debounce(function() {
          callNum += 1;
          document.getElementById(
            "weather"
          ).innerHTML += `<br>Weather fetched.. ${callNum}`;
        }, 1000)
      );
    </script>
  </body>
</html>

See it in action -

javascript-debounce-in-action

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things