Debounce Function in Javascript

Debouncing is a programming technique used to improve the performance and efficiency of certain functions, especially those triggered by events like scrolling, resizing, or typing. The purpose of debounce is to ensure that a function is not executed too frequently, particularly when the event that triggers it occurs rapidly or repeatedly.

When an event is triggered repeatedly in a short period, it can cause the associated event handler function to be executed multiple times in quick succession. This can lead to unnecessary processing and may impact the performance of the application or website.

Debouncing addresses this issue by adding a small delay before invoking the function. If the event is triggered again within that delay, the previous timer is canceled, and a new timer is set. The function is only executed when the delay has passed without any new events occurring.

Simplified Debounce Function in Javascript

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

In the above example, the debounce function takes two parameters: func, which is the function to be debounced, and delay, which is the time in milliseconds to wait before executing func.

...args gathers all the arguments passed to the function into an array args. This makes it possible to work with a variable number of arguments without explicitly defining them in the function signature.

The returned function is the debounced version of func, which can be assigned as an event handler. When the event occurs, this debounced function is called. If the event is triggered again within the specified delay, the previous timer is canceled, and a new timer is set.

What’s setTimeout function:

In JavaScript, setTimeout is a function that allows you to schedule the execution of a function (or the execution of a code snippet) after a specified delay in milliseconds. The syntax for setTimeout is as follows:

setTimeout(func, delay, arg1, arg2, ...);

func: This is the function that you want to execute after the specified delay. It can be an existing function defined elsewhere in your code or an anonymous function. delay: This is the time delay in milliseconds before the func is executed. For example, if you set delay to 1000, the func will be executed after 1000 milliseconds (1 second). arg1, arg2, โ€ฆ: (Optional) These are additional arguments that you can pass to the func. If you need to pass specific data to the function when it’s executed, you can include these arguments.

setTimeout(() => {
  func.apply(this, args);
}, delay);

It uses an arrow function (a concise way of defining functions) as the func to be executed. The apply method is then called on func, which allows you to call the function with a given this value and arguments provided as an array (args).

The this value within the func will be preserved, and any arguments passed to the setTimeout function after the delay value will be used as arguments for the func.

For example, if you had the following code:

function myFunction(a, b) {
  console.log(a + b);
}
const args = [2, 3];
const delay = 1000;
setTimeout(() => {
  myFunction.apply(this, args);
}, delay);

After 1000 milliseconds, the function myFunction will be called with arguments 2 and 3, and it will log 5 to the console.

How to use debounce function in event handler:

function handleScroll() {
  // Do something when scrolling stops
  console.log('Scroll event handled.');
}
// Debounced version of the handleScroll function with a delay of 300 milliseconds
const debouncedHandleScroll = debounce(handleScroll, 300);
// Attach the debounced function as the event handler for the scroll event
window.addEventListener('scroll', debouncedHandleScroll);

debouncing can ensure that the handleScroll function is called only once after the user has stopped scrolling for at least 300 milliseconds. This helps prevent unnecessary processing and ensures a smoother and more efficient user experience.

Using debounce function in handling key press user input or search box input.

debounce function can be used is in handling user input events like key presses or search box input. When a user types into an input field, it can trigger multiple events in rapid succession, potentially causing unnecessary and frequent updates or API requests.

A debounce function helps to optimize this scenario by delaying the execution of a function until the user stops typing for a specified period of time. If the user continues to type within that delay, the function call is canceled, and a new delay is started. This way, the function is only executed once after the user pauses their typing, reducing the number of calls and improving performance.

Let’s see how we could use debounce function defined earlier with an input field and event handler:

<!DOCTYPE html>
<html>
<head>
  <title>Debounce Example</title>
</head>
<body>
  <input type="text" id="searchInput" placeholder="Type something...">
  <div id="searchResults"></div>
  <script>
    // Debounce function implementation
    function debounce(func, delay) {
      let timerId;
      return function (...args) {
        clearTimeout(timerId);
        timerId = setTimeout(() => {
          func.apply(this, args);
        }, delay);
      };
    }
    // Simulate an API request for search results
    function performSearch(query) {
      // In a real application, this would fetch data based on the query
      console.log("Searching for:", query);
      document.getElementById("searchResults").textContent = "Search results for: " + query;
    }
    const delay = 500; // Debounce delay in milliseconds
    const debouncedSearch = debounce(performSearch, delay);
    document.getElementById("searchInput").addEventListener("input", function(event) {
      const searchQuery = event.target.value;
      debouncedSearch(searchQuery);
    });
  </script>
</body>
</html>

In this example, as the user types in the input field, the debouncedSearch function is called instead of the original performSearch function. The debounce function ensures that the performSearch function is executed only after the user has stopped typing for 500 milliseconds. The argument passed is serachQuery to the debouncedSearch function. This way, we prevent excessive API requests or processing while providing a smoother user experience.

Now, as you type in the input field, you will see that the “Searching for” message will only be logged after a short pause, and the search results will be displayed in the searchResults div after a short delay, rather than with every keystroke.

Where to use Debounce Function to Improve Performance:

The debounce function is a powerful utility that can be used in various scenarios where you need to control the frequency of function calls. Here are some common use cases for a debounce function:

  1. Search Input: As shown in the example provided earlier, a debounce function is often used in search input fields to delay the execution of the search function until the user stops typing, preventing excessive API calls and providing a smoother search experience.
  2. Autosave: When implementing an autosave feature in a text editor or form, a debounce function can be used to delay the save function until the user stops typing, reducing the number of unnecessary saves.
  3. Window Resize and Scroll Events: In scenarios where you need to respond to window resize or scroll events, a debounce function can be used to prevent excessive calculations or layout updates while the user is still interacting with the window.
  4. Real-Time Form Validation: In form validation, especially for live or real-time validation, a debounce function can be used to delay the validation function until the user stops typing in a form field, reducing the frequency of validation checks.
  5. Handling Input Events: In general, any situation where you need to handle frequent input events (e.g., key presses, mouse movements) and want to optimize the performance of the associated functions, a debounce function can be beneficial.
  6. API Requests: When making API requests in response to user interactions (e.g., infinite scroll, autocomplete suggestions), a debounce function can be used to throttle the requests, ensuring a more controlled flow of data and reducing server load.
  7. Delaying Expensive Operations: For any function that involves a time-consuming or resource-intensive operation, a debounce function can be used to delay the execution until the user stops interacting with the triggering event.
  8. Event Listeners: In scenarios where you attach multiple event listeners to an element, a debounce function can help reduce the number of calls made to the event handler functions.

The specific use cases for a debounce function may vary depending on the requirements of your application. Our primary goal is to prevent excessive and frequent calls to a function, making it more efficient and responsive to user interactions.

Don't Miss Out! Subscribe to Read Our Latest Blogs.

If you found this blog helpful, share it on social media.

Subscription form (#5)

Pin It on Pinterest

Scroll to Top