JavaScript Debounce Function

Anika Tabassum Era Feb 15, 2024
  1. JavaScript debounce Function Mechanism
  2. Use the lodash debounce Method for Better Performance
JavaScript Debounce Function

The debounce function drive is no explicit method that can be instantiated with the selectors. Its definition comprises a timer, returned function, and the contexts.

Other than this explicit debounce, we have jQuery debounce, lodash debounce, and underscore.js debounce. For visualization, we will set the examples in the following section.

The use case has probably been deprecated in the case of the jQuery debounce. There is a wide range of discussions and demonstrations yet available online, but the prior and latest versions of jQuery do not give any output; rather, the implementation says the $.debounce function does not exist.

However, we will examine two examples here, with the basic implementation of the debounce mechanism and the lodash debounce method. lodash is considered over the underscore.js convention.

So we will focus on the lodash debounce. Despite the basic system for this function, it can also take some other parameters.

This is also for the sake of better performance. You can redirect to this portal for a better understanding of lodash debounce.

JavaScript debounce Function Mechanism

The basic necessity of using the debounce function is to reduce unwanted actions and thus limit the function delay. Now the question might arise how is this making better performance by a delay.

Well, let’s consider an alert method of the window. What happens is that when we click on a triggered button corresponding to the alert, it will get fired.

But if the user repeats the click promptly one after another, you will see that the alert message gives an uneven preview or just one call action. This is due to a lack of good performance.

Every click or trigger is followed by an acceptance time of the signal, and the rest action is fired depending on it. When we are typing in a search box, each keypress gives updated filtered results.

This is also an implementation of this debounce function, which says, “no matter how much you click me or trigger me, I’ll only operate after the time I am asked to delay”. So, if anyone clicks a button abruptly, it will show its function after the time delay mentioned.

Here, in the instance, we have a timer, which is cleared every time the function is triggered. And when another click is directed, if the time delay is greater than the difference between the clicks, the function will reset the time count again.

And will follow the last click and start counting time and preview the task.

Code Snippet:

<html>
    <body>
        <button id="db">Debounce</button>
        <script>
            var btn = document.getElementById("db");
            const debounce = (func, delay) => {
                let Timer
                return function() {
                        clearTimeout(Timer)
                            Timer
                        = setTimeout(() => func.apply(this, arguments), delay)
                }
            }
            btn.addEventListener('click', debounce(function() {
                    alert("Executing after a sec!!")
                                    }, 1000));
        </script>
    </body>
</html>

Output:

JavaScript debounce Function Mechanism

So, our debounce function takes two parameters, the time delay and the context. On each call, the time delay is cleared and starts afresh.

Thus, a certain time delay is ensured, and despite user behavior on the trigger function, the internal debounce returns a debounced function that is nothing but the function we are working on bounded by a time frame.

Use the lodash debounce Method for Better Performance

In this specified lodash library, we have a predefined _.debounce method that takes the function, delay, and another optional parameter. So we do not require to explicitly define the clear and time-set restrictions.

Rather it is abstracted, and we can perform the debouncing feature just by calling it.

Code Snippet:

<html>
    <body>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
        <button id="db">Debounce</button>
        <script>
            var db = document.getElementById("db");
            var debounce = _.debounce(function(){
              alert("Wait for a sec!")
            }, 1000, {'leading':false})
            db.addEventListener('click', debounce);
        </script>
    </body>
</html>

Output:

Use lodash debounce Method for Better Performance

Anika Tabassum Era avatar Anika Tabassum Era avatar

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

LinkedIn Facebook

Related Article - JavaScript Debounce