Debouncing in JavaScript

Debouncing is a technique in programming that helps prevent time-consuming tasks from being triggered so frequently that they slow down the performance of a web page. In simpler terms, it controls how often a function is called.

Debouncing in JavaScript

In JavaScript, debouncing is commonly used to enhance browser performance. Sometimes, certain actions on a web page involve complex computations that take up time. If these actions are triggered too frequently, it can significantly impact the browser’s performance, especially since JavaScript operates on a single thread.

Approach

  • The button is linked to an event listener that invokes the debounce function when the button is clicked.
  • The debounce function takes two parameters: a function to be debounced and a delay in milliseconds.
  • Inside the debounce function, a variable named debounceTimer is declared. This variable is crucial for executing the debounced function after a specified delay.
  • When the button is clicked, the debounce function is called. If the button is clicked only once, the debounced function is scheduled to run after the specified delay.
  • If the button is clicked again before the end of the delay, the initial delay is canceled using clearTimeout(debounceTimer).
  • A new delay timer is initiated, effectively resetting the debounce process. This mechanism ensures that the debounced function is only executed after the user stops clicking the button for the specified delay duration.
  • The core idea behind debouncing is to start with a timeout of 0.
  • If the debounced function is called again within the delay period, the timer is reset to the specified delay.
  • Ultimately, when the timeout occurs, the debounced function is executed. The process repeats for each call to the debounce function, effectively resetting the timer and introducing a delay for each invocation.

Example: Below is the Implementation of the above approach.

HTML
<!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>

Output:

Application

Debouncing finds practical use in various scenarios within web development. For instance, it can be used in implementing suggestive text features. Here, we wait for the user to pause typing for a few seconds before offering suggestions. With debouncing, we ensure that suggestions are only provided after a brief pause, preventing constant updates with each keystroke.

Another application of debouncing is in content-heavy webpages like Facebook and Twitter. As users scroll through their feeds, frequent firing of the scroll event can lead to performance issues, especially with numerous videos and images to load. By implementing debouncing, we can regulate the frequency of the scroll event, reducing the performance impact and creating a smoother browsing experience.

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.