防抖和节流

124 阅读1分钟

防抖和节流

1 防抖 (debounce)

1.1 作用

优化input的回调,降低ajax请求的频率

image.png

1.2 简单理解

image.png

1.3 简单代码实现

<template>
<input @input="testDebounce" v-model="keyword" />
</template>

<script>
export defalut {
  data () {
    return {
      ...
      keyword:'',
      timer: null
    }
  },
  methods:{
  ...
    testDebounce () {
      clearTimeout(this.timer)
      // console.log(this.timer)
      this.timer = setTimeout(() => {
        console.log(this.keyword)
      }, 500)
    }
  }
}
</script>

image.png

1.4 应用场景

可以在做搜索页面的时候,用书输入关键词时使用

testDebounce () {
  clearTimeout(this.timer)
  this.timer = setTimeout(() => {
    this.doAjax() // 发送请求,搜索关键字
  }, 500)
},
doAjax () {
 ...
}

1.5 截图

image.png

2 节流 (throttle)

2.1 作用

优化input的回调,降低ajax请求的频率

2.2 简单理解

image.png

2.3 代码实现

<template>
<input @input="testThrottle" v-model="keyword" />
</template>

<script>
export defalut {
  data () {
    return {
      ...
      keyword:'',
      startTime: Date.now()
    }
  },
  methods:{
  ...
    testThrottle () {
      // 节流测试
      const dt = Date.now() // 获取当前时间戳,ms为单位
      if (dt - this.startTime > 500) {
        console.log(this.keyword)
        this.startTime = dt
      } else {
        console.log('当前时间戳是', dt, '距离上一次执行不够500ms,不执行')
      }
    }
  }
}
</script>

image.png

2.4 应用场景

和防抖类似

2.5 截图

image.png

3 关于防抖节流

3.1 共同点

降频

3.2 不同点

1.防抖:某个时间内不能再次触发,一旦触发,就要重新计时
2.节流:限制相邻两次调用的时间间隔