Why does console.log("Called"); is called only once inside the debounce function?

Viewed 44

In below code why console.log("Called"); is only coming once though the debounce function is called again and again on every keyup event

 const txt = document.getElementById("text");
        let label = document.getElementById("label");
    
        function debounce(fun,delay) {
            let time;
            console.log("Called");
            return function(args) {
                if(time) {
                    clearTimeout(time);
                }
                time = setTimeout(() => {
                    fun(args);
                },delay);
            }
        }
    
        function callback(e) {
            label.innerHTML = e.target.value;
        }
        
        txt.addEventListener("keyup", debounce(callback,700));
    </script>
<html>
    <body>
        <input type="text" id="text" placeholder="Enter something..."><br />
        <label id="label"></label>
    </body>
</html>

?

1 Answers

It is being called while setting up the event listener. Even before any keyup event. If you want to log when the function is being called. Log it inside the function that is being returned from debounce.

Related