vue 防抖函数和节流函数

函数防抖(Debounce):指触发事件后在 n 秒内函数只执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。如:搜索框,滚动条
函数节流(throttle):指连续触发事件但在 n 秒中只执行一次,避免某些事件频繁触发。如:按钮点击

第一步:定义公共防抖和节流函数

export default {

  /**
   * 函数防抖
   * 触发事件后在n秒后执行,如果n秒内又触发事件,则重新计算时间
   */
  debounce(fn, wait = 1000) {
    let timer;
    return function () {
      let context = this;
      let args = arguments;
      if (timer) clearTimeout(timer);
      timer = setTimeout(() => {
        fn.apply(context, args);
      }, wait)
    }
  },

  /**
   * 函数节流
   * 触发事件立即执行,但在n秒内连续触发则不执行
   */
  throttle(fn, wait = 1000) {
    let timer;
    return function () {
      if (timer != null) return;
      let context = this;
      let args = arguments;
      fn.apply(context, args);
      timer = setTimeout(() => {
        timer = null;
      }, wait);
    }
  },
}

注意
防抖和节流函数中 return 的函数不能使用箭头函数,如果使用箭头函数则 this 就会指向 globalFunction,就会有问题

第二步:新建 Vue 组件

第三步:引用 globalFunction 并在 methods 中使用

说明:
globalFunction 类的 debounce、throttle 返回的一个函数,就相当于

btnDebounce() {
   let context = this;
   let args = arguments;
   console.log(this);
   console.log(args);
 }

所以可以拿到当前 this 和 arguments 参数,因为 argument 获取的是一个类似数组的对象,所以可以通过调用函数的 apply 方法来传递参数

你可能感兴趣的:(前端,vue,防抖函数,节流函数)