如何防抖动

在开发中我们会接触到很多事件,有些事件会频繁的触发。如下:

  • window 的 resize、scroll
  • mousedown、mousemove
  • keyup、keydown
  • ……

以Vue为例,了解事件如何频繁的触发:

Vue代码:

<template>
  <div
    ref="container"
    class="container"
  >
    {{ number }}
  </div>
</template>

<script>
export default {
  data () {
    return {
      number: 0
    }
  },
  mounted () {
    this.getUserAction()
  },
  methods: {
    getUserAction () {
        this.$refs.container.onmousemove = () => {
          this.number ++
        }
    }
  }
}
</script>

<style scoped>
  .container {
    font-size: 50px;
    color: #fff;
    text-align: center;
    line-height: 100px;
    background-color: #434343;
    height: 100px;
  }
</style>

效果图

在这里插入图片描述

可以看到鼠标在左右滑动的时候一直触发onmousemove事件。这个例子简单,如果复杂的回调函数或者是请求事件。假设1秒钟触发了onmousemove事件为100次。每个回调事件或者请求事件必须在1000 / 100 = 10ms之内完成,否则就会出现卡顿。

如何防抖
第一版:

<template>
  <div
    ref="container"
    class="container"
  >
    {{ number }}
  </div>
</template>

<script>
export default {
  data () {
    return {
      number: 0,
      timeout: null
    }
  },
  mounted () {
    this.getUserAction()
  },
  methods: {
    getUserAction () {
        this.$refs.container.onmousemove = () => {
          this.debounce()
        }
    },
    debounce () {
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        this.number++
      }, 1000)
    }
  }
}
</script>

<style scoped>
  .container {
    font-size: 50px;
    color: #fff;
    text-align: center;
    line-height: 100px;
    background-color: #434343;
    height: 100px;
  }
</style>

在这里插入图片描述

现在随便怎么移动鼠标在1000ms之内只会触发一次。触发事件次数从以前的100+变成了1次。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值