防抖与截流

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);
        }
    }
}

你可能感兴趣的:(防抖与截流)