1.防抖就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。
let tellInput = document.querySelector("input");
tellInput.addEventListener("input", antiShake(demo, 1000));
//封装防抖
function antiShake(fn, wait) {
let timeOut = null;
return (args) => {
if (timeOut) clearTimeout(timeOut);
timeOut = setTimeout(fn, wait);
};
}
function demo() {
console.log("发起请求");
}
2.节流就是指连续触发事件但是在 n 秒中只执行一次函数。节流会稀释函数的执行频率
let box = document.querySelector(".one");
box.addEventListener("touchmove", throttle(demo, 2000));
function throttle(event, time) {
let timer = null;
return () => {
if (!timer) {
timer = setTimeout(() => {
event();
timer = null;
}, time);
}
};
}