JavaScript Debouncing vs. Throttling (Optimizing Event Listeners)

In this tutorial, we will learn about javascript debouncing vs. throttling (optimizing event listeners) with some cool and easy examples. In many situations, you might have to come up with this type of requirements.

What is Debouncing in JavaScript?

Debouncing is a technique used to limit how often a function is called. It ensures that a function runs only after a specified delay has passed since the last time it was triggered.

Example:

You’re typing in a search box, and you want to send a request only after the user stops typing for 500ms.

What is Throttling in JavaScript?

Throttling ensures a function is called at most once every X milliseconds, even if the event keeps firing.

Example:

When the user scrolls a page, and you want to handle scroll updates once every 200ms, no matter how fast the user scrolls.

Debouncing and throttling are techniques used to optimize performance by controlling how often a function tied to events (like scroll or resize) gets executed. Debouncing delays the function call until a certain amount of time has passed since the last event—ideal for actions like search input or window resizing. Throttling limits the function to run at regular intervals, regardless of how many times the event fires—useful for events like scrolling or mouse movements. Both help reduce unnecessary function calls and improve app responsiveness.

Implementation JavaScript Debouncing vs. Throttling

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Debounce vs Throttle Demo</title>
  <style>
    body { font-family: sans-serif; padding: 2rem; }
    input { padding: 0.5rem; width: 200px; margin-right: 1rem; }
  </style>
</head>
<body>

  <h2> Debounce vs Throttle</h2>

  <input id="searchBox" type="text" placeholder="Type to search (debounce)" />
  <div id="scrollArea" style="height: 100px; overflow-y: scroll; border: 1px solid #ccc; margin-top: 1rem;">
    <div style="height: 600px;">Scroll inside this box</div>
  </div>

  <script>
    // Debounce Implementation
    function debounce(fn, delay) {
      let timeout;
      return function(...args) {
        clearTimeout(timeout);
        timeout = setTimeout(() => fn.apply(this, args), delay);
      };
    }

    //  Throttle Implementation
    function throttle(fn, limit) {
      let lastCall = 0;
      return function(...args) {
        const now = Date.now();
        if (now - lastCall >= limit) {
          lastCall = now;
          fn.apply(this, args);
        }
      };
    }

    //  Example: Debounced input handler
    const handleInput = debounce((event) => {
      console.log(` Debounced Search Query: ${event.target.value}`);
    }, 500);

    document.getElementById('searchBox').addEventListener('input', handleInput);

    // Example: Throttled scroll handler
    const handleScroll = throttle(() => {
      console.log(` Throttled Scroll Event at ${new Date().toLocaleTimeString()}`);
    }, 1000);

    document.getElementById('scrollArea').addEventListener('scroll', handleScroll);
  </script>

</body>
</html>

Output:

🔍 Debounced Search Query: a
🔍 Debounced Search Query: ab
🔍 Debounced Search Query: abc
📜 Throttled Scroll Event at 10:00:01 AM
📜 Throttled Scroll Event at 10:00:02 AM

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top