实现说明
函数节流以函数 throttle、throttled为骨架。
使用要点
- 把
throttle当作 API:导入它,其余代码可以忽略。
常见问题
依赖情况复杂吗?
一点也不复杂:零依赖,没有要锁版本或审计的东西。 文件在加载时定义 throttle、throttled。
主要签名是 export function throttle(fn, intervalMs)
核心语句
pendingTimer = setTimeout(() => {
pendingTimer = null;
lastCall = Date.now();
fn.apply(this, args);
}, remaining);
return fn.apply(this, args);
代码示例
export function throttle(fn, intervalMs) {
let lastCall = 0;
let pendingTimer = null;
return function throttled(...args) {
const now = Date.now();
const remaining = intervalMs - (now - lastCall);
if (remaining <= 0) {
lastCall = now;
return fn.apply(this, args);
}
if (pendingTimer === null) {
pendingTimer = setTimeout(() => {
pendingTimer = null;
lastCall = Date.now();
fn.apply(this, args);
}, remaining);
}
};
}