Debouncing

Debouncing

Debouncing is a programming technique used to limit the number of invocations of a time-consuming function in order to improve the application performance.

const debounce = (func, delay) => {
    let timerId = null;

    if (timerId) {
        clearTimeout(timerId);
    }

    return function() {
        let context = this;
        let args = arguments;

        timerId = setTimeout(() => {
            func.apply(context, args);
        }, delay);
    }
}

In the above code, debounce() is a higher-order function that takes in two parameters: func & delay and returns another function.

func represents the function that is to be debounced and delay refers to the amount of time until which that function is to be debounced.

timer represents the previous timerId, if exists. It is used to cancel any previously established timeout set by calling setTimeout().