防抖与截流

2019-07-30  本文已影响0人  EmilWong
function debounce (fn, wait, immediate) {
    let timer = null;
    return function () {
        let args = arguments, context = this;
        if (immediate && !timmer) {
            fn.apply(context, args)
        }
        if (timer) clearTimeout(timer)
        timer = setTimeout(()=>{
            fn.apply(context, args);
        }, wait);
    }
} 
function throttle(fn, wait, immediate) {
    let timer = null, callNow = immediate;
    return function () {
        let args = arguments, context = this;
        if (callNow) {
            fn.apply(context, args);
            callNow = false;
        }
        if (!timer) {
            timer = setTimeout(() => {
                fn.apply(context, args);
                timer = null;
            }, wait);
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读