1.普通版(立即执行)
javascript
function throttle(fn, delay) {
let start = Date.now();
return function(...args) {
let end = Date.now();
if (end - start >= delay) {
fn.apply(this, args);
start = end;
}
}
}
2.延迟执行
javascript
function throttle(fn, delay) {
let timer = null;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
}
}
3.支持立即执行和尾调用
ini
function throttle(fn, delay, options = {}) {
let timerId = null;
let lastRunTime = 0;
const { leading = true, trailing = false } = options; // 默认立即执行,不尾调用
return function (...args) {
const now = Date.now();
const remaining = delay - (now - lastRunTime);
if (remaining <= 0) {
// 冷却期已过,可以执行
if (timerId) {
clearTimeout(timerId);
timerId = null;
}
if (leading) {
fn.apply(this, args);
}
lastRunTime = now;
} else if (!timerId && trailing) {
// 处于冷却期内,且允许尾调用,设置定时器用于尾执行
timerId = setTimeout(() => {
fn.apply(this, args);
lastRunTime = Date.now();
timerId = null;
}, remaining);
}
};
}