如何防抖动

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

  • 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次。

你可能感兴趣的:(如何防抖动)