Introduction

Debouncing: A technique used in JavaScript to limit the rate at which a function is executed. This is particularly useful when an event triggers a function call too frequently, like window resizing or scrolling.

Why Use Debouncing?

How Debouncing Works?

Implementing Debouncing in JavaScript

1. Basic Debounce Function

function debounce(func, delay) {
  let timer;
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => func.apply(this, args), delay);
  };
}

2. Example Usage

// Function to be debounced
function searchQuery(query) {
  console.log(`Searching for ${query}`);
}

// Debounce with a 300ms delay
const debouncedSearch = debounce(searchQuery, 300);

// Attach to input event
document.getElementById('searchInput').addEventListener('input', (e) => {
  debouncedSearch(e.target.value);
});

3. Explanation

Another Example Of Debouncing

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button id="debounce">
    Debounce
  </button>
  <script>
    let button = document.getElementById("debounce");

    const debounce = (func, delay) => {
      let debounceTimer;
      return function() {
        const context = this;
        const args = arguments;
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(() => func.apply(context, args), delay);
      };
    };

    button.addEventListener('click', debounce(function() {
      alert("Hello\nNo matter how many times you" +
        " click the debounce button, I get " +
        "executed once every 3 seconds!!");
    }, 3000));
  </script>
</body>

</html>

Real-World Applications

Conclusion

Thank You For Reading !! DO like the Article and provide feedback.