防抖,节流

173 阅读1分钟
function dobunce(fn, wait = 50, immediate = false) {
    if (!wait) {
        wait = 50;
    }
    if (typeof immediate !== 'boolean') immediate = false;
    let timer = null;
    
    return function(...args) {
        const exectorImmediate = immediate && !timer;
        clearTimeout(timer);
        timer = setTimeout(() => {
            timer = null;
            !immediate && fn.call(this, ...args);
        }, wait);
        // 第一次立即执行
        exectorImmediate && fn.call(this, ...args);
    }
}


function throttle(fn, wait = 50) {
    let timer = null;
    let prevTime = 0;
    return function(...args) {
        const currentTime = +new Date();
        const times = wait - (currentTime - prevTime);

        if (times <= 0) {
            prevTime = +new Date();
            fn.call(this, ...args);
        } else if (!timer) {
            timer = setTimeout(() => {
                clearTimeout(timer);
                prevTime = +new Date();
                timer = null;
                fn.call(this, ...args);
            }, wait);
        }
    }
}