防抖节流
防抖什么的非常简单
function debounce(fn, delay) {
let timer;
return function (...args) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeOut(() => {
fn(...args);
}, delay);
};
}
function debounce2(fn, delay) {
let timer;
return function (...args) {
if (timer) {
clearTimeout(timer);
}
let callNow = !timer;
timer = setTimeout(() => {
timer = null;
}, delay);
if (callNow) {
fn(...args);
}
};
}
节流也是非常的简单,节流就是减少触发的次数
throttle(func, delay) {
let status = true;
return function(...args) {
if (!status) return false;
status = false;
setTimeout(() => {
func.apply(this, args);
status = true;
}, delay);
};
},
function throttle(fn, wait) {
let previous = 0;
return function (...args) {
let now = new Date();
if (now - previous > wait) {
fn.apply(this, args);
previous = now;
}
};
}