← 中文资源

简体中文版本

函数节流

节流限制函数执行频率,每段时间间隔内最多调用一次,适用于高频触发的滚动与尺寸变化处理。

阅读英文原文

实现说明

函数节流以函数 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);
    }
  };
}