SOURCE

//debounce
function debounce(cb, delay) {
    let timer = null;

    const fn = function (...args) {
        if (timer) {
            clearTimeout(timer);
        };

        timer = setTimeout(() => {
            cb.apply(this, args);
            timer = null;
        }, delay)
    };

    fn.cancel = function () {
        if (timer) {
            clearTimeout(timer);
        };
        timer = null;
    };

    return fn;
};

//throttle
function throttle(cb, delay) {
    let timer = null;
    let lastTime = 0;

    const fn = function (...args) {
        const now = Date.now();
        const remain = delay - (now - lastTime);

        if (remain <= 0) {
            if (timer) {
                clearTimeout(timer);
                timer = null;
            };
            cb.apply(this, args);
            lastTime = now;
        } else if (!timer) {
            timer = setTimeout(() => {
                cb.apply(this, args);
                lastTime = Date.now();
                timer = null;
            }, remain)
        }
    };

    fn.cancel = function () {
        if (timer) {
            clearTimeout(timer);
        };
        timer = null;
    };

    return fn;
}
console 命令行工具 X clear

                    
>
console