close
The Wayback Machine - https://web.archive.org/web/20250207230414/https://www.geeksforgeeks.org/debouncing-in-javascript/
Open In App

Debouncing in JavaScript

Last Updated : 10 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Debouncing is a technique in programming that helps improve the performance of web applications by controlling the frequency at which time-consuming tasks are triggered. If a task is triggered too often—like when a user types quickly or rapidly clicks a button—it can lead to performance issues. Debouncing provides a solution by limiting how frequently a function can be executed.

What is Debouncing in JavaScript?

In JavaScript, debouncing is commonly used to enhance browser performance by ensuring that expensive operations (like complex calculations, API calls, or DOM updates) are executed only when necessary. JavaScript operates in a single-threaded environment, meaning it can only handle one operation at a time. When certain actions are triggered too frequently, such as during continuous scrolling or typing, it can overload the browser and cause sluggish performance.

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 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.



Next Article

Similar Reads

three90RightbarBannerImg