1. 防抖
- 为什么会有防抖?
短时间内多次触发同一事件,会造成资源浪费。
- 防抖原理:
如果 n 秒内触发多次同一事件,每次触发都会重新计算时间(清除之前计算时间的定时器),直到最后一次触发时 n 秒后不再触发该事件,才去执行该事件。
- 好处:
频繁触发事件,最终只会执行一次事件处理函数
- 【举例】搜索框中输入搜索词进行查询
不加防抖:每次键入搜索词都会触发 input 框的 input 事件进行搜索词查询(多次请求)
加了防抖:n 秒内如果再次输入搜索词,则重新计算时间,直到输入搜索词 n 秒后不再输入时,才触发input事件进行搜索词查询(一次请求) - 代码示例
<template>
<div>
<!-- 搜索词输入框 -->
<input type="text" v-model="searchWords" @input="inputHandler" placeholder="请输入关键词" />
</div>
</template>
<script>
export default {
data() {
return {
searchWords: '', // 搜索词
timer: null // 延时器返回值
}
},
methods: {
inputHandler() {
clearTimeout(this.timer) // 清除延时器
this.timer = setTimeout(() => {
console.log('搜索词----', this.searchWords)
}, 1000)
}
}
}
</script>
<style lang='scss' scoped>
</style>
2. 节流
- 为什么会有节流?
防止多次触发同一事件,造成资源浪费
- 节流原理
设置一个节流阀,每一次触发事件时打开节流阀,在 n 秒内执行一次事件结束后,关闭节流阀(用节流阀变量来控制是否执行代码)
- 好处
每间隔 n 秒触发一次事件
- 【举例】移动的鼠标
不加节流:鼠标每移动 1px 就会触发一次事件
加了节流:鼠标 n 秒内无论移动多远距离只触发一次事件, - 代码示例
<template>
<div class="page" @mousemove="mousemoveHandler($event)"></div>
</template>
<script>
export default {
data() {
return {
timer: null,
aaa: 1
}
},
methods: {
mousemoveHandler(e) {
if (!this.timer) {
// 打开节流阀
this.timer = setTimeout(() => {
this.aaa++
console.log('aaa----', this.aaa)
this.timer = null // 关闭节流阀
}, 500)
}
}
}
}
</script>
<style lang='scss' scoped>
.page {
width: 100%;
height: 100%;
}
</style>
- 类似的例子还有:用户如果多次点击轮播图切换图片按钮,我们需要限制在 n 秒内多次点击不允许切换
- 设置节流阀,在用户每次点击切换轮播图时打开节流阀,n 秒后关闭节流阀