朱丽叶

导航

防抖(debounce)与节流(throttle)

// 函数防抖。事件被触发n秒后再执行函数,如果在n秒内又被触发,则重新计时,频繁触发事件,只会执行一次函数。
//  函数防抖 在短时间内事件被多次触发,只会调用一次函数

  1. 导出模块
    /**
  • 函数防抖
  • @param fn
  • @param delay
  • @returns
  • @constructor
    */

export const Debounce = (fn, time) => {
let delay = time || 500;
let timer;
return function() {
let args = arguments;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
timer = null;
fn.apply(this, args);
}, delay);
};
};

/**

  1. 函数节流

  2. @param fn

  3. @param interval

  4. @returns

  5. @constructor
    */
    export const Throttle = (fn, time) => {
    let last;
    let timer;
    let interval = time || 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);
    }
    };
    };

  6. 使用
    methods: {
    // 注意箭头函数与普通函数的this指向问题,所以这里使用普通函数。
    changeRdCost: Debounce(function(e) {}

}

posted on 2021-03-26 09:51  朱丽叶  阅读(78)  评论(0)    收藏  举报