JavaScript Debouncing

This tutorial will cover the debouncing technique in JavaScript along with how to implement it using the debounce method.

What is Debouncing?

Debouncing serves as a technique in JavaScript that aims to enhance the performance of a browser. Situations may arise where certain functionalities within a webpage require extensive computations. Repeated application of such functionalities can significantly impact the browser's performance due to JavaScript's nature as a single-threaded language. The concept of debouncing involves a programming approach to ensure that resource-intensive tasks do not lead to a decline in webpage performance. Essentially, debounce methods refrain from immediate execution upon invocation. Instead, they introduce a delay before running the designated tasks. Subsequent calls to the same process result in the cancellation of the previous task, followed by a reset of the timer.

Debouncing and throttling are closely related techniques that enhance the performance of web applications, even though they serve different purposes. Debouncing is employed when focusing on the end result, such as delaying an action until a user has completed a task, like typing in a search bar to fetch typeahead search results. On the other hand, throttling is preferred for controlling the frequency of intermediate states to maintain a consistent pace of actions.

Implementation of debouncing

Consider an example to observe how the debounce method is implemented in a program.

Example

const debounce = (func, wait) => {
  let timeout;
  return function mainFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(delay, wait);
  };
};

A higher-order function that returns another function is known as a debounce function. It is used to create a closure around the func and wait function parameters and the timeout variable to hold their values. The definitions of the following variables are:

  • Func: It is the func function that we want to execute after the debounce time.
  • Wait: The time after the last received action that the debounce function can wait until executing func.
  • Timeout: The timeout function is the value that is used to indicate a running debounce.
  • Example:

Consider an illustration to grasp the concept of the debouncing function in JavaScript. In the provided scenario, a button is linked to an event listener that triggers a debounce function. The debounce function takes two arguments: a function and a numerical value representing time. A timer is established to execute the debounce function once a specific duration has elapsed.

Example

<!DOCTYPE html>
<html> 
<body>
<h1>JavaScript Debounce</h1>
<input type = "button" id="debounce" value = "Click Here">
<script>
var button = document.getElementById("debounce");
const debounce = (func, wait) => {
    let debounceTimer
    return function() {
        const context = this
        const args = arguments
            clearTimeout(debounceTimer)
                debounceTimer
            = setTimeout(() => func.apply(context, args), wait)
    }
} 
button.addEventListener('click', debounce(function() {
        alert("Hello\n This message will be displayed after 3 seconds, and no matters how many times we click the button.")
}, 4000));
</script>
</body>
</html>

Upon running the code provided, the resulting output will appear as depicted below:

In the screenshot provided, there is a button labeled as "Click here". Upon clicking this button, a warning dialog pops up showing an alert message. This functionality refreshes with each interaction. If the button is clicked within a delay of 4 seconds, the original timer is reset, and a fresh timer begins. The task is accomplished using the clearTimeOut function.

Implementation of debounce function with immediate function

The debounce implementation provided generates a function that delays its execution until a specified period of inactivity has passed. Once the delay of N milliseconds elapses without any further invocations, the function is triggered. When the function is invoked with the original function as a parameter, it is executed immediately and then postponed until the specified interval has lapsed before being triggered again.

Example

function debounce(func, wait, immediate) {
  var timeout;
  return function mainFunction() {
    var cont = this;
    var args = arguments;    
    var later = function() {
      timeout = null;
      if (!immediate) func.apply(cont, args);
    };
    var callNow = immediate && !timeout;	
    clearTimeout(timeout);
    timeout = setTimeout(delay, wait);	
    if (callNow) func.apply(cont, args);
  };
};

The debounce function generates a new function that can be assigned to event listeners of a given function along with a specified time interval.

Example

var returnedFunction = debounce(function() {
}, 3000);
window.addEventListener('resize', returnedFunction);

Example:

Let's consider an example to illustrate the application of the debounce function in conjunction with the immediate function.

Example

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Debounce</h1>
    <button id="debounce"> 
        Click here
    </button>     
    <script> 
    var button = document.getElementById("debounce");  
    const debounce = (func, wait, immediate)=> {
    var timeout;
    return function executedFunction() {
        var cont = this;
        var args = arguments;         
        var later = function() {
        timeout = null;
        if (!immediate) func.apply(cont, args);
        };
        var callNow = immediate && !timeout;        
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(cont, args);
        };
    };
    button.addEventListener('click', debounce(function() { 
            alert("This message will be displayed after 3 seconds, and no matters how many times we click the button.") 
                            }, 3000)); 
    </script> 
 </body>
</html>

Upon running the aforementioned code snippet, the resulting output will be displayed as depicted in the image provided.

In the provided image, we can observe the presence of a button labeled "Debounce." Upon clicking this button, an alert message is displayed. Dismissing the alert message can be done by clicking on the "Ok" button.

Application Uses

Debouncing is a technique commonly employed in scenarios such as implementing auto-suggestions for text input fields. It involves introducing a delay after each user input to ensure that suggestions are only provided once the user pauses typing. This approach helps in preventing frequent suggestions during typing. In the context of websites with heavy content like Facebook and Twitter, where users engage in continuous scrolling activities, debouncing plays a crucial role. The excessive firing of scroll events due to numerous videos and images can significantly impact performance. Therefore, debouncing becomes essential to optimize the scroll functionality in such cases.

Input Required

This code uses input(). Please provide values below: