Vue防抖与节流的使用介绍

概念

1. 防抖

防抖策略(debounce):是当事件被触发后,延迟n秒后再执行回调函数,如果在这n秒内事件被再次触发,则重新计时.

好处是:它能够保证用户在频繁触发某些事件的时候,不会频繁的执行回调,只会被执行一次.

防抖的概念:如果有人进电梯(触发事件),那电梯将在10秒钟后出发(执行事件监听器),这时如果又有人进电梯了(在10秒内再次触发该事件),我们又得等10秒再出发(重新计时)。

防抖的应用场景::

用户在输入框连续输入一串字符时,可以通过防抖策略,只在输入完后,才执行查询的请求,这样可以有效减少请求次数,节约请求资源.

2. 节流策略

节流策略(throttle):,可以减少一段时间内事件的触发频率.

节流阀的概念:

高铁的卫生间是否被占用,由红绿灯控制,假设一个每个人上洗手间要五分钟,则五分钟之内别人不可以使用,上一个使用完毕之后,将红灯设置为绿灯,表示下一个人可以使用了.下一个人在使用洗手间时需要先判断控制灯是否为绿色,来知晓洗手间是否可用.

–节流阀为空,表示可以执行下一次操作,不为空,表示不能使用下次操作.

–当前操作执行完之后要将节流阀重置为空,表示可以执行下次操作了.

–每次执行操作之前,先判断节流阀是否为空

节流策略的应用场景:

1)鼠标不断触发某事件时,如点击,只在单位事件内触发一次.

2)懒加载时要监听计算滚动条的位置,但不必要每次滑动都触发,可以降低计算频率,而不必要浪费CPU资源.

Vue中的使用

项目中新建一个throttleDebounce.js文件

export default {
// 防抖
debounce: function (fn, t) {
    let delay = t || 500;
    let timer;
    return function () {
      let th = this;
      let args = arguments;
      if (timer) {
        clearTimeout(timer);
      }
      timer = setTimeout(function () {
        timer = null;
        fn.apply(th, args);
      }, delay);
    }
  },
  // 节流
  throttle: function (fn, t) {
    let last;
    let timer;
    let interval = t || 500;
    return function () {
      let th = this;
      let args = arguments;
      let now = +new Date();
      if (last && now - last < interval) {
        clearTimeout(timer);
        timer = setTimeout(function () {
          last = now;
          fn.apply(th, args);
        }, interval);
      } else {
        last = now;
        fn.apply(th, args);
      }
    }
  }
}

FileConvert.vue文件

引入

import throttleDebounce from '@/utils/throttleDebounce.js'
// convertRes  是el-button绑定的点击事件
methods:{
convertRes: throttleDebounce.throttle(function() {
      //  需要节流的事件,我这里是接口的调取
      this.convertResFinal()  
    }, 500),
//  节流的事件
convertResFinal() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          this.hexBtnLoading = true
          const params = {
            arch: this.form.arch,
            addr: this.form.addr,
            hexdump: this.form.hexdump
          }
          try {
            const res = await getVexConvertRes(params)
            if (res.code === 200) {
              
            }
          } catch (error) {
          }
        }
      })
    },
}

原文地址:https://blog.csdn.net/weixin_44834981/article/details/128325465