防抖和节流都是为了处理一定时间范围内事件的高频率触发行为
防抖:事件触发后一定时间内函数只会执行一次,如果在这时间内事件再次被触发,则重新计时。
function debounce(fn, delay = 300) {
let timer;
return function () {
if (timer) {
clearTimeout(timer);
}
const args = [...arguments]
timer = setTimeout(() => {
fn.apply(null, args);
}, delay);
};
}
节流:事件只会在设置的时间间隔内执行一次。
function throttle(fn, delay = 300) {
let timer = null;
return function () {
if (timer) {
return;
}
const args = [...arguments];
timer = setTimeout(() => {
fn.apply(null, args);
timer = null;
}, delay);
};
}
function throttle(fn, delay = 300) {
let preTime = Date.now();
return function () {
const nowTime = Datre.now();
const args = [...arguments];
if (nowTime - preTime >= delay) {
preTime = Date.now();
fn.apply(null, args);
}
};
}
function throttle(fn, delay = 300) {
let timestamp = 0;
let timer = null;
return function throttled(force = false, args) {
const now = Date.now();
if (force || now - timestamp > delay) {
if (timer) {
clearTimeout(timer);
timer = null;
}
timestamp = now;
fn.apply(null, args);
}
if (!timer) {
timer = setTimeout(() => {
timer = null;
timestamp = Date.now();
fn.apply(null, args);
}, delay);
}
};
}