[underscore 源码实现] throttle 节流 与

2020-02-02  本文已影响0人  小黄人get徐先生

throttle 与 debounce

只要涉及到连续事件或频率控制相关的应用都可以考虑到这两个函数,比如:

throttle

_.throttle(func, wait, options)
options = {
  leading: false
}
或
options = {
  trailing: false
}
两者只能设置其中一个
    _.now = Date.now;

    _.throttle = function(func, wait, options) {

        let lastTime = 0;
        let context;
        let args;
        let timeout;

        const later = function() {
            // 这里 leading 为 false 时,置 lastTime 值为 0 是因为下次调用 if(!lastTime ...) 这样就为 true,会执行对应语句
            lastTime = options.leading === false ? 0 : _.now();
            timeout = null;
            func.apply(context, args);
        };

        return function() {
            const now = _.now();
            if (!lastTime && options.leading === false) {
                lastTime = now;
            }
            const remaining = wait - (now - lastTime);
            context = this;
            args = arguments;
            console.log(remaining);
            if (remaining <= 0) {
                if (timeout) {
                    clearTimeout(timeout);
                    timeout = null;
                }
                lastTime = now;
                func.apply(context, args);
            } else if (!timeout && options.trailing !== false) {
                timeout = setTimeout(later, wait);
            }
        };
    };

debounce

_.debounce(func, wait, immediate)
    _.debounce = function(func, wait, immediate) {
        let timeout;
        let result;

        const later = function(context, args) {
            timeout = null;
            if (args) result = func.apply(context, args);
        };

        return function(...args) {
            if (timeout) clearTimeout(timeout);
            if (immediate) {
                const callNow = !timeout;
                // 这里直接传递 later 回调函数没有传参,所以在 later 内部逻辑不会执行 func;这里的作用是为了定时
                timeout = setTimeout(later, wait);
                if (callNow) result = func.apply(this, args);
            } else {
                timeout = setTimeout(function() {
                    later(this, args);
                }, wait);
            }
            return result;
        };
    };
上一篇 下一篇

猜你喜欢

热点阅读