Debounce in JavaScript

Debounce in JavaScript generally states that you want to delay a function in particular event. Events such as mouse move, click etc. Lets take an example:- you have an event of mouse move on a button. When you move your mouse over the button it will fire the event many times. To avoid this we will use debounce technique to delay the function by few sec so that only last event is capture and rest of all the previous events are cancelled.

let debounce = function(fn, delay){
    let debounceTimer;
    return function(){
        debounceTimer != undefined ? clearTimeout(debounceTimer) : '';
        debounceTimer = setTimeout(() => {
            fn();
        }, delay);
    }
}
function consoleme(){
    console.log("I am clicked");
}
let button = document.getElementById("button");
button.addEventListener("click", debounce(consoleme, 1000));

Here we have a generic debounce function that accepts two parameters. One is function itself and another is delay. Declared a variable debounceTimer, which as the name suggests, is used to actually call the function, received as a parameter after an interval of ‘delay’ milliseconds.

Leave a Reply

Your email address will not be published. Required fields are marked *