节流和防抖
节流 throttle
官方的解释:当持续触发事件时,保证一定时间段内只调用一次事件处理函数。
简单的比喻:LOL 英雄的技能,每次释放技能之后,技能就会处于 CD 中,只有技能冷却完了,才能释放下一次技能。
const throttle = (func, time) => {
let timer = null; // 技能 CD 时间
return (...args) => {
// 判断技能是否还在冷却 CD 中
if (timer) {
return;
}
func(...args);
timer = setTimeout(() => {
timer = null;
}, time * 1000);
};
};
function x() {
console.log("使用闪现技能!");
}
const f = throttle(x, 2);
// 第一次调用 f(),使用技能 闪现,之后只有等待 2s CD时间时候,才能再次使用。
防抖 debounce
官方解释:当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次;如果设定的时间到来之前,又一次触发了事件,就重新开始延时。
简单比喻:LOL 英雄回城,回城时间(假定3s)内,没有被小兵,对面玩家攻击(没有触发事件),3s 后就会回城;但是如果在 3s 时间之内,你被攻击了(触发事件),你就只能再次重新开始计时,然后等待 3s 之后回城。
const debounce = (func, time) => {
let timer = null;
return (...args) => {
// 假设重新按下回城,就打断上一次回城
if (timer !== null) {
clearTimeout(timer);
}
// 重新回城
timer = setTimeout(() => {
func(...args); // 回城后调用 func
timer = null;
}, time * 1000);
};
};
const b = () => {
console.log("回城成功!");
};
const f = debounce(b, 3);