Open In App

Debouncing in JavaScript

Improve
Improve
Like Article
Like
Save
Share
Report

Debouncing is a programming practice used to ensure that time-consuming tasks do not fire so often, that it stalls the performance of the web page. In other words, it limits the rate at which a function gets invoked.

Debouncing in JavaScript is a practice used to improve browser performance. There might be some functionality in a web page that requires time-consuming computations. If such a method is invoked frequently, it might greatly affect the performance of the browser, as JavaScript is a single-threaded language. 

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:

shvjahsfvjsfhvjshdfbkajsflsdjgn

Application

Debouncing can be applied in implementing suggestive text, where we wait for the user to stop typing for a few seconds before suggesting the text. thus, on every keystroke, we wait for some seconds before giving out suggestions. Another application of debouncing is in content-loading webpages like Facebook and Twitter where the user keeps on scrolling. In these scenarios, if the scroll event is fired too frequently, there might be a performance impact, as it contains lots of videos and images. Thus the scroll event must make use of debouncing.

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.



Last Updated : 20 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads