SOURCE

// 节流: 场景使用于第一次有效,开关锁, 例如多次提交表单,页面滚动处理事件
// 一定时间内只触发一次
function throttle(fn, delay) {
    let timer = null;
    return function() {
        if(timer) {
            return false;
        }
        let that = this;
        let args = arguments;
        fn.apply(that, args);
        timer = setTimeout(() => {
            clearTimeout(timer);
            timer = null;
        }, delay || 500)
    }
}

// 防抖: 场景用于最后一次有效,清零,如 ,输入框匹配
function debounce(fn, delay) {
    let timer = null;
    return function() {
        let that = this;
        let args = arguments;
        clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(that, args);
        }, delay || 500)
    }
}

// 节流
// 时间戳版本
function throttle(fn, delay) {
    let last = 0;
    return function() {
        let now = Date.now();
        if(now >= delay + last) {
            fn.apply(this, arguments);
            last = now;
        }
        else {
            console.log('距离上次调用的时间差不满足');
        }
    }
}

function resize(e) {
    console.log("窗口大小改变了");
}
// window.addEventListener('resize', throttle(resize, 500));

// 定时器版本
function throttle2(fn, delay) {
    let timer = null;
    return function() {
        if(!timer) {
            fn.apply(this, arguments);
            timer = setTimeout(() => {
                timer = null;
            }, delay);
        }
        else {
             console.log('距离上次调用的时间差不满足');
        }
    }
}

// window.addEventListener('resize', throttle2(resize, 500));


// 防抖,在最后一次触发有效
function debounce(fn, delay) {
    let timer = null;
    return function() {
        clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(this, arguments);
        }, delay)
    }
}
console 命令行工具 X clear

                    
>
console