vue防抖和节流

代码优化时需要用到防抖,就去网上找了许多代码,但无一例外,都出了一点问题:闭包没有成功,每次进入都会重新定义 timer。

参考地址[https://blog.csdn.net/qq_19323867/article/details/89366846]

下面给出我的解决方案:

将timer提到函数外面,设定为全局变量
欢迎大佬在评论区提出错误原因
/**
 * 函数防抖 (只执行最后一次点击)
 * @param fn
 * @param delay
 * @returns {Function}
 * @constructor
 */
let timer1 = null; //防抖,将timer提到函数外面,设定为全局变量
let timer2 = null; //节流
export const Debounce = (fn, t) => {
    let delay = t || 500; 
    return function () {
        let args = arguments;
        // let timer1 = null
        // console.log(timer1);
        if(timer1){
            clearTimeout(timer1);
        }
        timer1 = setTimeout(() => {
            fn.apply(this, args);
            timer1 = null;
        }, delay);
    }
};

// 使用
/*import {Debounce} from '@/common/debounceThrottle.js'
Debounce(() => {
    //要执行的函数
}, 200)() */

/**
 * 函数节流
 * @param fn
 * @param interval
 * @returns {Function}
 * @constructor
 */
export const Throttle = (fn, t) => {
    let last;
    let interval = t || 500;
    return function () {
        let args = arguments;
        let now = +new Date();
        if (last && now - last < interval) {
            clearTimeout(timer2);
            timer2 = setTimeout(() => {
                last = now;
                fn.apply(this, args);
            }, interval);
        } else {
            last = now;
            fn.apply(this, args);
        }
    }
};

 

posted on 2020-09-07 15:13  嗨哆嚒  阅读(304)  评论(1编辑  收藏  举报