paint-brush
Improve API Performance by Using Debounce in JavaScriptby@zt4ff
429 reads
429 reads

Improve API Performance by Using Debounce in JavaScript

by Kayode OluwasegunNovember 6th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Debouncing is a technique that ensures long-running operations are not fired so often. It delays the execution of that particular program. A common example is a search operation fired whenever a user types a query in an input field. Debouncing the operation would mean waiting for the user to stop typing for a particular time (usually milliseconds) before running the search operation. This may save you a great deal of money if you use this technique in your web application. In a mock project, we can create a mock search page to see how this may function in real applications.

Company Mentioned

Mention Thumbnail
featured image - Improve API Performance by Using Debounce in JavaScript
Kayode Oluwasegun HackerNoon profile picture


Imagine your web application makes requests to an API endpoint and each request has a price, debouncing the request operation may save you a great deal of money.


There are cases where you have long-running operations and these operations are in a position where they can be fired frequently by your application users. Such operations invoked continuously may affect the performance of your web application.


Debouncing is a technique that ensures long-running operations are not fired so often. It delays the execution of that particular program.


A common example is a search operation fired whenever a user types a query in an input field. Debouncing the operation would mean waiting for the user to stop typing for a particular time (usually milliseconds) before running the search operation.


Let’s write a simple implementation here:

function debounce(func, time = 300) {
  let timer;

  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => func.apply(this, args), time);
  };
}


Now we can create a mock project to see how this may function in a real application.

<!-- index.html -->
<html>
  <head>
    <title>Mock Search Page</title>
  </head>
  <body>
    <label for="search">Enter your search</label>
    <input id="search" type="text" name="search" />
    <script>
      const nameElement = document.querySelector("#search");

      function debounce(func, time = 500) {
        let timer;

        return (...args) => {
          clearTimeout(timer);
          timer = setTimeout(() => func.apply(this, args), time);
        };
      }

      const debouncedSearchFunction = debounce((event) => {
        console.log("querying: " + event.target.value + "....");
      });

      nameElement.addEventListener("keyup", (event) => {
        debouncedSearchFunction(event)
      });
    </script>
  </body>
</html>


The code above, debounce returns a function and keeps a local variable timer (they both form a closure). timer acts like a state to manage the timing.


In the event listener callback, we call the function that is returned by debouce and, as we can see, the arguments in this function are passed to the func argument using the method [Function.prototype.apply](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply).

Conclusion

As I mentioned in the introduction of this article, in a case where each of your requests to an API endpoint is paid and the actions of a user can fire the operations. Debouncing the operations can be done to create a form of throughput per time (milliseconds).


Also Published here