函数防抖、节流

2022-01-13  本文已影响0人  INGME

函数防抖:n秒内只要触发事件,就重新计时,事件处理函数的程序将永远不会被执行

/**
 * 函数防抖
 * @param  {[fn]} 回调方法
 * @param  {[time]} 延迟时间
 * @param  {[immediate]} 是否立即执行
 */

function debounce(fn, time, immediate) {
    var timer = null,
        result;

    var debounced = function() {
         var context = this,
             args = arguments;

        if(timer) clearTimeout(timer);
    
        if(immediate) {
            // 如果已执行,不再执行
           var callNow = !timer;
           timer = setTimeout(function() {
                timer = null;
            }, time);
            if(callNow) {
                result = fn.apply(context, args);
            }
        } else {
            timer = setTimeout(function() {
               result = fn.apply(context, args);
            }, time)
        }
        return result;
    }
    
    debounced.cancel = function() {
        clearTimeout(timer);
        timer = null;
     }

    return debounced;
}

函数节流:事件被触发,n秒内只执行一次事件处理函数

/**
 * 函数节流
 * @param  {[fn]} 回调方法
 * @param  {[delay]} 延迟时间
 */

function throttle(fn, delay) {
    var timer = null,
        begin = new Date().getTime();

    return funcion() {
        var context = this,
            args = arguments,
            now = new Date().getTime();

        clearTimeout(timer);

        if(now - begin >= delay) {
            fn.apply(context, args);
            begin = now;
        } else {
            timer = setTimeout(function() {
                fn.apply(context, args);
            }, delay)
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读