防抖节流
节流防抖都是用来在函数中减少不必要的重复操作
1.防抖 debounce
防抖是在一段时间内,多次触发一个事件,只有最后一次才会生效
js
const debounce = (cb, timeout) => {
let timer;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
cb();
}, timeout);
};
};如下示例,点击按钮,圆环会开始加载,当不停的点击时,只有最后一次点击结束才会开始加载
2.节流 throttle
防抖是多次触发一个事件,会先执行第一个事件,若第一个事件还没有执行结束,则后面的事件不会生效,
只有当第一个事件结束之后,再才能够继续执行事件
js
const throttle = (fn, delay) => {
let lastTime = 0;
let timer = null;
return function (...args) {
const now = Date.now();
if (now - lastTime < delay) {
// 如果还在节流时间内,设置一个定时器
if (timer) return; // 避免重复设置定时器
timer = setTimeout(() => {
lastTime = Date.now();
fn.apply(this, args);
timer = null; // 重置定时器
}, delay - (now - lastTime));
} else {
// 当时间超过了节流间隔,立即执行
lastTime = now;
fn.apply(this, args);
}
};
};不停点击下列示例,可看到效果
节流示例
0
