函数防抖与函数节流

115 阅读1分钟
  • 函数节流是指一定时间内js方法只运行一次
  • 函数防抖是指频繁触发的情况下,只有足够的空闲时间,才运行一次
/**
 * 函数防抖
 * fn 执行函数
 * delay 等待时间
 * immediate true:立即执行 false:延迟执行
*/
function debounce(fn, delay, immediate) {
    let timer;
    return function () {
        let _this = this,
            args = arguments;
        if (timer) clearTimeout(timer);
        if (immediate) {
            let callNow = !timer;
            timer = setTimeout(() => {
                timer= null;
                fn.apply(_this, args);
            }, delay);
            if (callNow) fn.apply(_this, args);
        } else {
            timer = setTimeout(() => {
                fn.apply(_this, args);
            }, delay);
        }
    }
}
/**
 * 函数节流
 * fn 执行函数
 * delay 等待时间
 * immediate true:立即执行 false:延迟执行
*/
function throttle (fn, delay, immediate) {
    let timer, startTime = 0;
    return function () {
        let _this = this,
            args = arguments;
        if (immediate) {
            let now = Date.now();
            if (now - startTime > delay) {
                fn.apply(_this, args);
                startTime = now;
            }
            return;
        }
        if (!timer) {
            timer = setTimeout(function () {
                timer = null;
                fn.apply(_this, args);
            }, delay);
        }
    }
}