How To Debouncing Using JavaScript Example?


Share:
Published By: Admin, Published On: Nov 09, 2021, Category: Javascript


Hello Friends,

Now let's see example of how to debouncing example. We will check debouncing using javascript. This is a short guide on debouncing in javascript. Let's get started with how to check debouncing in javascript.

Here i will give you many example how to check debouncing using javascript.

Example : 1
<!DOCTYPE html>  
<html> 
    <head>
        <title>How To Debouncing Using JavaScript? - MyWebtuts.com</title>
    </head>  
    <body>  
        <h3>How To Debouncing Using JavaScript? - MyWebtuts.com</h3>  
        <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("MyWebtuts.com\n This message will be displayed after 3 seconds")  
            }, 4000));  
        </script>  
    </body>  
</html>
Output :
MyWebtuts.com
This message will be displayed after 3 seconds
Example : 2
<!DOCTYPE html>  
<html> 
    <head>
        <title>How To Debouncing Using JavaScript? - MyWebtuts.com</title>
    </head>  
    <body>  
        <h3>How To Debouncing Using JavaScript? - MyWebtuts.com</h3>  
        <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("MyWebtuts.com, This message will be displayed after 3 seconds")
            }, 3000));  
        </script>  
    </body>  
</html>
Output :
MyWebtuts.com, This message will be displayed after 3 seconds

It will help you...

Share: