美文网首页
函数的节流和防抖

函数的节流和防抖

作者: 白小纯Zzz | 来源:发表于2019-12-09 11:59 被阅读0次
/**
 * 函数防抖 (只执行最后一次点击)
 * @param fn
 * @param delay
 * @returns {Function}
 * @constructor
 */
export const Debounce = (fn, t) => {
    let delay = t || 500;
    let timer;
    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);
        }
    }
};

用法

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

相关文章

网友评论

      本文标题:函数的节流和防抖

      本文链接:https://www.haomeiwen.com/subject/gtsbgctx.html