DEV Community

Cover image for Debounce and Throttling in js
Sarat Nayak
Sarat Nayak

Posted on

Debounce and Throttling in js

Note: to understand, you should have a basic understanding of setTimeout (used to schedule delayed function execution) and closures in JavaScript (which allow functions to remember variables from their outer scope even after the outer function has finished executing). These concepts are essential for grasping how the timer is preserved across multiple calls and how function execution is controlled over time.

Before going to the definition, we first need to know why we need that.

In many real-world scenarios, especially in web applications, certain events like typing in an input field, scrolling, resizing the window, or moving the mouse can fire very frequently—sometimes dozens or hundreds of times per second. If we attach heavy operations to these events, such as API calls, DOM updates, or data processing, it can lead to poor performance and an unresponsive user experience.

To avoid this, we use techniques like debounce and throttle as performance optimization tools. They help us limit or control how often a function gets executed during such repetitive events. That’s a brief overview to give you a sense of what these concepts aim to solve. Now let’s explore how they differ and when to use each.

Debounce :

Debounce is a mechanism that delays the execution of a function until a specified amount of time has passed after the last occurrence of an event.

It's commonly used in situations like typing in an input field, where the function (e.g., a search or API call) should only run after the user has stopped typing.

Example :

Take an input field where a user is typing something. Instead of calling an API function on every keystroke, we apply a debounce mechanism to delay the function call.

The API is only called after a specified amount of time has passed since the user last typed. This helps reduce unnecessary function calls and improves performance, especially for real-time search or suggestions.

index.html file

<body style="background-color: black; color: white">

    <div>    
    <input type="text"  id="inputBox" placeholder="Debounce checking..">
    </div>


    <script src="debounce.js"></script>
    <!-- <script src="throttling,js"></script> -->
</body>
Enter fullscreen mode Exit fullscreen mode

debounce.js file

  // Debounce function: Delays execution of the passed-in function (func)
// until after 'delay' milliseconds have passed since the last call
function debounce(func, delay) {
    let timer; // Stores the timer ID for setTimeout

    return function (...args) {
        clearTimeout(timer); // Clear the previous timer on each new input
        timer = setTimeout(() => {
            func(...args); // Call the original function after delay
        }, delay);
    };
}

// Input handler function: Logs the current value of the input field
function handelInput(event) {
    console.log(event.target.value); // Print the input value to the console
}

// Get reference to the input field with id="inputBox"
const inputFeild = document.getElementById("inputBox");

// Create a debounced version of the input handler with 1 second (1000ms) delay
const debounceInput = debounce(handelInput, 1000);

// Add event listener to input field for "input" event
// This triggers the debounced handler — the real function (handelInput)
// will only be called if the user stops typing for 1 second
inputFeild.addEventListener("input", debounceInput);

Enter fullscreen mode Exit fullscreen mode

Throttling

Throttling is a mechanism that limits the execution of a function to at most once every specified amount of time, regardless of how frequently the event occurs during that period.

It’s commonly used in situations like window resizing, scrolling, or mouse movements, where the event fires continuously. Throttling ensures that the function (e.g., updating UI or syncing scroll position) runs at regular intervals, instead of on every single event, helping to maintain performance and responsiveness.

Example :

Take an input field where a user is typing something. Instead of calling an API function on every keystroke, we apply a throttle mechanism to control the rate at which the function is called.

With throttling, the API is called at regular intervals (e.g., once every 300 milliseconds), regardless of how frequently the user types. This ensures the function executes consistently without overwhelming the system, helping to maintain smooth performance during continuous typing, especially in high-frequency input scenarios.

index.html

<body style="background-color: black; color: white">

    <div>    
    <input type="text"  id="inputBox" placeholder="Debounce checking..">
    <button>click</button>
    </div>


    <!-- <script src="debounce.js"></script> -->
    <script src="throttling,js"></script>
Enter fullscreen mode Exit fullscreen mode

throttling.js

// Throttling function: ensures the given function (func) 
// is executed at most once every 'delay' milliseconds
function throttling(func, delay) {
  let timer; // Used to track the delay timer

  return function (...args) {
    // Only execute if the timer is not active
    if (!timer) {
      func(...args); // Call the original function immediately

      // Start the timer to prevent further calls until delay ends
      timer = setTimeout(() => {
        timer = null; // Reset timer after delay to allow next call
      }, delay);
    }
  };
}

// Event handler for input field: logs the current value to console
function handelInput(event) {
  console.log(event.target.value);
}

// Get reference to the input field with id="inputBox"
const inputFeild = document.getElementById("inputBox");

// Create a throttled version of the input handler with a 300ms interval
const throttlingInput = throttling(handelInput, 300);

// Add an event listener to the input field for "input" event
// This uses the throttled handler, so handelInput will be called 
// at most once every 300 milliseconds, even if the user types rapidly
inputFeild.addEventListener("input", throttlingInput);

Enter fullscreen mode Exit fullscreen mode

Top comments (0)