防抖(debounce)
1.search搜索数据,用户在不断输入值时,用防抖来节约请求资源。
2.window触发resize的时候,不断的调整浏览器窗口大小会不断的触发这个事件,用防抖来让其只触发一次。
let timer = null; //设置定时器
const debounce= () => {
clearTimeout(timer); // 清除定时器
timer = setTimeout(() => {
console.log('需要防抖的函数'); // 添加需要防抖的方法
}, 500); // 设置防抖时间
};
节流(throttle)
1.鼠标不断点击触发,mousedown(单位时间内只触发一次)。
2.监听滚动事件,比如是否滑到底部自动加载更多,用throttle来判断。
let flag = true; // 设置节流条件
const throttle= () => {
if (!flag) {
return;
}
flag= false;
console.log('需要节流的函数'); // 添加需要节流的方法
setTimeout(() => {
flag= true;
}, 3000); // 设置节流时间
};