Typescript / javascript minimal debounce

Date: 2021-05-05

Source: https://www.freecodecamp.org/news/javascript-debounce-example/

function debounce(func: Function, timeout = 300) {
    let applyAgain = false;
    let timer: number;
    return (...args: any) => {
        if (!timer) {
            func.apply(this, args);
        } else {
            applyAgain = true;
        }
        clearTimeout(timer);
        timer = setTimeout(() => {
            timer = undefined;
            if (applyAgain) {
                func.apply(this, args);
                applyAgain = false;
            }
        }, timeout);
    };
}
50360cookie-checkTypescript / javascript minimal debounce