防抖(多次触发 只执行最后一次)
防抖策略(debounce)是当事件被触发后,延迟n秒后再执行回调,如果在这n秒内事件又被触发,则重新计时。
Vue写法:
<template>
<a-input @change="handleChange"></a-input>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
data() {
return {
// 定时器
timer: null,
}
},
methods: {
handleChange() {
if (this.timer) {
clearTimeout(this.timer);
}
this.timer = setTimeout(() => {
// 业务逻辑
console.log('=============');
}, 200);
}
},
})
</script>
JavaScript写法:
let timer = null;
if (this.timer) {
clearTimeout(this.timer);
}
this.timer = setTimeout(() => {
// 业务逻辑
console.log('=============');
}, 200);
节流(规定时间内 只触发一次)
节流策略(throttle),控制事件发生的频率,如控制为1s发生一次,甚至1分钟发生一次。
Vue写法:
<template>
<a-input @change="handleChange"></a-input>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
data() {
return {
//开始时间
firstTime: 0,
}
},
methods: {
handleChange() {
/* 获取当中时间的事件戳 */
let nowTime = new Date();
if (nowTime - this.firstTime < 1000) {
//不要让代码往后面走,就是不要触发事件
return;
}
//下一个时间段,又是从头开始
this.firstTime = nowTime;
// 业务逻辑
console.log('=============');
}
},
})
</script>
JavaScript写法:
let firstTime = 0;
let nowTime = new Date();
if (nowTime - this.firstTime < 1000) {
return;
}
this.firstTime = nowTime;
// 业务逻辑
console.log('=============');