console
function throttle(fn, delay, options = { leading: true, trailing: true }) {
let timer = null;
let previous = 0;
return function (...args) {
const now = Date.now();
if (!options.leading && previous === 0) {
previous = now;
}
const remaining = delay - (now - previous);
if (remaining <= 0) {
if (timer) {
clearTimeout(timer);
timer = null;
}
previous = now;
fn.apply(this, args);
} else if (!timer && options.trailing) {
timer = setTimeout(() => {
previous = options.leading ? Date.now() : 0;
timer = null;
fn.apply(this, args);
}, remaining);
}
};
}
const throttledFn = throttle(() => {
console.log('触发了', Date.now());
}, 2000, { leading: true, trailing: true });
window.addEventListener('scroll', throttledFn);