8

vue 中使用防抖和节流,防止重复点击或重复上拉加载

 2 years ago
source link: https://www.geekjc.com/post/5ddfd80ed908ff68625647e4
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

vue 中使用防抖和节流,防止重复点击或重复上拉加载

时间: 11/28/2019作者: frontend-联合编辑浏览量: 2140
/**
 * 函数防抖 (只执行最后一次点击)
 * @param fn
 * @param delay
 * @returns {Function}
 * @constructor
 */
export const Debounce = (fn, t) => {
    let delay = t || 500;
    let timer;
    console.log(fn)
    console.log(typeof fn)
    return function () {
        let args = arguments;
        if(timer){
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            timer = null;
            fn.apply(this, args);
        }, delay);
    }
};
/**
 * 函数节流
 * @param fn
 * @param interval
 * @returns {Function}
 * @constructor
 */
export const Throttle = (fn, t) => {
    let last;
    let timer;
    let interval = t || 500;
    return function () {
        let args = arguments;
        let now = +new Date();
        if (last && now - last < interval) {
            clearTimeout(timer);
            timer = setTimeout(() => {
                last = now;
                fn.apply(this, args);
            }, interval);
        } else {
            last = now;
            fn.apply(this, args);
        }
    }
};

vue中的用法:

...
methods:{
    getAliyunData:Throttle(function(){
    ...
     },1000),
}
...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK