手写防抖节流
防抖
js
function debounce(fn, delay) {
let timer = null;
return function () {
let context = this,
args = [...arguments];
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(() => fn.apply(context, args), delay);
};
}
节流
js
function throttle(fn, delay) {
let preTime = Date.now();
return function () {
let context = this,
args = [...arguments],
nowTime = Date.now();
if (nowTime - preTime > delay) {
preTime = nowTime;
fn.apply(context, args);
}
};
}
function throttle(fn, delay) {
let timer = null;
return function () {
let context = this,
args = [...arguments];
if (!timer) {
timer = setTimeout(() => {
fn.apply(context, args);
timer = null;
}, delay);
}
};
}