js节流&防抖

152 阅读1分钟
export default class ThrottleUtil {
    /**
     * 节流
     * 每隔一段时间,只执行一次函数。
     * @param delay 判定时间
     * @param action 实际方法
     * @param options 选项对象:
     * {
     *      toggleLastArg // boolean。在delay时间内多次触发的话,是否选择最后一次触发的参数来执行,默认为false(只触发第一次点击)
     * }
     * @returns {Function} 回调,回调实际的方法
     */
    static throttle = (delay, action = () => {}, options) => {
        let last = 0;
        const toggleLastArg = !!(options && options.toggleLastArg);
        let toggleLastArgTimer = null;
        return function (...args) {
            if (toggleLastArgTimer) clearTimeout(toggleLastArgTimer);
            const curr = new Date().getTime();
            if (curr - last > delay) {
                action.call(this, ...args); // call this是为了让外部拿到正确的this值
                last = curr;
            } else if (toggleLastArg) {
                toggleLastArgTimer = setTimeout(() => {
                    action.call(this, ...args);
                }, delay);
            }
        };
    }

    /**
     * 防抖
     * 定义:多次触发事件后,事件处理函数只执行一次,并且是在触发操作结束时执行
     * 原理:对处理函数进行延时操作,若设定的延时到来之前,再次触发事件,则清除上一次的延时操作定时器,重新定时。
     * @param delay 判定时间
     * @param action 实际方法
     * @returns {Function} 回调,回调实际的方法
     */
    static debounce = (delay, action = () => {}) => {
        let timer = null;
        return function (...args) {
            if (timer) {
                clearTimeout(timer);
            }
            timer = setTimeout(() => {
                action.call(this, ...args); // call this是为了让外部拿到正确的this值
            }, delay);
        };
    }
}

防抖和节流区别


简单理解就是,

  • 节流类似打游戏,持续点击鼠标射击,但只会在一定的时间间隔内发送一次,可以间隔性不断发射,节省资源(可执行多次);
  • 防抖好比是一些高危的操作,为防止“手抖”,直接撤销之前的操作,只执行最后一次操作(只执行一次)。