防抖和节流

防抖和节流

防抖

重新开始,只执行最后一次

搜索框输入、文本编辑器实时保存

1
<input type="text" class="ipt" @keyup="handleKeyUp($event)" />
1
2
3
4
5
6
7
8
9
const timerId = ref(null); // 使用 ref 来存储定时器 ID
const handleKeyUp = function (event) {
if (timerId.value !== null) {
clearTimeout(timerId.value); // 清除之前的定时器
}
timerId.value = setTimeout(() => {
console.log(event.target.value); // 打印输入框的值
}, 1000);
};

节流

中间禁用,只执行最先一次

快速点击、鼠标滑动、scroll事件、下拉加载、视频播放器记录时间

1
2
3
4
5
6
7
8
9
const timerId = ref(null); // 使用 ref 来存储定时器的 ID
const handleKeyUp = function (event) {
if (timerId.value === null) {
timerId.value = setTimeout(() => {
console.log(event.target.value); // 打印输入框的值
timerId.value = null; // 清空定时器 ID
}, 1000);
}
};