函数节流
方法一 时间戳
function throttle(fn, wait) {
let preTime = 0;
return () => {
const now = new Date();
if (now - preTime > wait) {
fn();
preTime = now;
}
};
}
方法二 定时器
function throttle(fn, wait) {
let timer;
return () => {
if (!timer) {
timer = setTimeout(() => {
timer = null;
fn();
}, wait);
}
};
}
函数的防抖
function debounce(fn, wait) {
let timer;
return () => {
clearTimeout(timer);
timer = setTimeout(fn, wait);
};
}
网友评论