加载中...
防抖和节流
发表于:2022-03-15 | 更新于:2023-10-24 | 分类: 项目

防抖(Debounce)和节流(Throttle)都是用来控制某个函数在一定时间内触发次数,两者都是为了减少触发频率,以便提高性能或者说避免资源浪费。

防抖:指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。

<input @keyup="sends(list)"  />
  data() {
    return {
      timeout: null
    }
  },
  methods: {
    debounce(fn, item) {
      // 先判断定义的变量是不是没有被赋值定时器,
      if (this.timeout !== null) {
        // 如果被赋值了就清除定时器
        clearTimeout(this.timeout)
      }
      this.timeout = setTimeout(() => {
        fn()
      }, item)
    },
    sends() {
      // 封装里面第一个值接收的是一个函数,所以这里就得传一个函数
      this.debounce(() => {
        console.log('防抖被调用了')
      }, 3000)
    }
  }

节流:指连续触发事件但是在 n 秒中只执行一次函数。

方法一
<input @keyup="sends(list)" />
  data() {
    return {
      canUse: true
    }
  },
  methods: {
    throttle(fn, item) {
      // 如果为true,就触发技能,否则就不能触发
      if (this.canUse) {
        // 触发技能后,关闭开关
        fn()
        this.canUse = false
        // 在3秒后打开开关
        setTimeout(() => {this.canUse = true}, item)
      }
    },
    sends() {
      this.throttle(() => {
        console.log(this)
      }, 3000)
    }
  }
方法二
<el-button :loading="handLoading" type="primary" @click="handleConfirm" >确定</el-button>
  data() {
    return {
      handLoading: false
    }
  },
  methods: {
    handleConfirm() {
      this.handLoading = true
      // 触发事件
      console.log('节流')
      setTimeout(() => {
        this.handLoading = false
      }, 300)
    }
  }
上一篇:
node
下一篇:
项目总结
本文目录
本文目录