JS防抖和节流
Breezli防抖和节流
防抖
重新开始,只执行最后一次
搜索框输入、文本编辑器实时保存
1
| <input type="text" class="ipt" @keyup="handleKeyUp($event)" />
|
1 2 3 4 5 6 7 8 9
| const timerId = ref(null); 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); const handleKeyUp = function (event) { if (timerId.value === null) { timerId.value = setTimeout(() => { console.log(event.target.value); timerId.value = null; }, 1000); } };
|