Debouncing Method in JavaScript


In JavaScript, a debounce function makes sure that your code is only triggered once per user input. Search box suggestions, text-field auto-saves, and eliminating double-button clicks are all use cases for debounce.

Debouncing in JavaScript is a practice used to improve browser performance. There might be some functionality in a web page that requires time-consuming computations. If such a method is invoked frequently, it might greatly affect the performance of the browser, as JavaScript is a single-threaded language.

A Debounce function is a higher-order function that returns another function, to create closure around the function parameters (func, timeout) and the timer variable.

  1. func: is a function that you want to execute after the debounce time
  2. timeout: The amount of time you want the debounce function to wait after the last received action before executing func.
  3. timer: The value used to indicate a running debounce.

sample Code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Debouncing in Javascript</title>
  </head>
  <body>
    <h5>Debouncing in Javascript</h5>
    <input type="text" id="txtInput" />
    <script src="script.js"></script>
  </body>
</html>

script.js

const txtInput = document.getElementById("txtInput");

txtInput.addEventListener("keyup", function () {
  optimizeFunction();
});

let counter = 0;
const getDataFromApi = () => {
  console.log("Getting Data....", counter++);
};

const debounceMethod = function (fn, delay) {
  let timer;
  return function () {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, arguments);
    }, delay);
  };
};

const optimizeFunction = debounceMethod(getDataFromApi, 300);

List of Programs


JS Practical Questions & Answers


JS Practical Project