防抖
定义:
n 秒后再执行该事件,若在 n 秒内被重复触发,则重新计时
应用场景:
按钮点击太快重复提交
调整浏览器窗口,resize次数过于频繁,造成计算过多
手机号、邮箱验证输入检测等
debounce(callback, delay) {
let timer;
return function() {
let that = this;
let args = arguments;
if(timer) {
clearTimeout(timer)
}
timer = setTimeout(function(){
callback.apply(that, args)
}, delay);
}
}
eg:
<template>
<div>
<input type="text" @keyup="debounce" />
</div>
</template>
<script>
export default {
data() {
return {
timer: null
}
},
methods: {
debounce() {
if(this.timer) {
clearTimeout(this.timer)
}
this.timer = setTimeout(() => {
console.log("防抖...")
this.timer = null
}, 2000)
}
}
}
</script>
节流
定义:
在一个单位时间内,只能触发一次函数,如果这个单位时间内触发多次函数,只有一次生效。
应用场景:
滚动加载,加载更多或滚到底部监听
搜索框,搜索联想功能
thorttle(callback, delay) {
let timer;
return function () {
let that = this;
let args = arguments;
if(!timer) {
timer = setTimeout(function(){
timer = null;
callback.apply(that, args)
}, delay)
}
}
}
eg:
<template>
<div>
<button @click="throttle">按钮</button>
</div>
</template>
<script>
export default {
data() {
return {
timer: null,
lastTime: null
}
},
methods: {
throttle() {
let now = +new Date()
if(this.lastTime && now - this.lastTime < 200) {
clearTimeout(this.timer)
} else {
this.lastTime = now
this.timer = setTimeout(() => {
console.log("节流...")
this.lastTime = +new Date()
}, 1000)
}
}
}
}
</script>
防抖 VS 节流
相同:
都可以通过使用 setTimeout 实现
目的都是,降低回调执行频率。节省计算资源
不同:
防抖,在一段连续操作结束后,处理回调,利用clearTimeout和 setTimeout实现。
防抖,关注一定时间连续触发的事件,只在最后执行一次,
节流,一段时间内只执行一次
节流,在一段连续操作中,每一段时间只执行一次,频率较高的事件中使用来提高性能