Skip to content

节流

有两种实现方式

  1. 时间戳
  2. timeout
ts
const throttle = (func, wait: number = 500) => {
  let time;

  return function (this: any, ...args: any[]) {
    const now = Date.now();
    if (time && now - time < wait) {
      return;
    }
    time = now;

    const context = this;

    func.apply(context, args);
  };
};

timeout 的方式与节流很像

js
if (timer) return;

timer = setTimeout(() => {
  // 执行函数
  todo run some code;

  // 这里一定要清空
  timer = null;
}, wait);

示例