如何实现一个可靠的setInterval替代方案?考虑页面不可见的情况

解读

国内面试中,这道题表面问“定时器”,实则考察三件事:

  1. 是否知道浏览器在页面不可见时会主动“节流”甚至“挂起”setInterval,导致间隔漂移、丢帧、回调堆积;
  2. 能否利用 Page Visibility API、Web Worker、时间戳补偿、RAF 降级等多种机制,给出“业务层可靠、资源层友好”的完整方案;
  3. 是否具备工程化思维:可配置、可取消、内存安全、异常隔离、TypeScript 友好,并能在 SSR/Node 环境优雅降级。

一句话:让定时器“准点、不堆积、不掉线、不耗电”。

知识点

  1. 浏览器节流策略:页面隐藏后,setInterval 最小粒度被放大到 1000 ms 甚至暂停(Chrome 自 88 起对未激活 Tab 的定时器进行“对齐暂停”)。
  2. Page Visibility API:document.hidden / visibilitychange 事件,是判断“可见性”的唯一标准。
  3. Web Worker:运行在独立线程,不受页面生命周期影响,可精准 postMessage 打点。
  4. 时间戳补偿:记录“期望时间点”与“实际时间点”的差值,在页面恢复后一次性“追帧”或“丢弃”。
  5. requestAnimationFrame:页面可见时利用 60 FPS 刷新信号做“视觉级”精准触发;隐藏时自动降级到 Worker。
  6. 异常隔离:回调内 throw 不能打断整个调度器,需 try/catch 并上报。
  7. 内存泄漏防控:清除闭包引用、移除事件监听、关闭 Worker。
  8. 多端降级:Node 环境无 DOM,直接退化为 setInterval + 时间戳漂移检测;小程序环境用 wx.nextTick 模拟。

答案

/**
 * 可靠定时器:页面可见时用 RAF,隐藏时用 Worker,支持暂停、继续、销毁
 * 兼容浏览器、WebView、SSR、Node
 */
class ReliableInterval {
  private readonly callback: () => void;
  private readonly interval: number;
  private timerId: number | NodeJS.Timeout | null = null;
  private worker: Worker | null = null;
  private last = 0;               // 期望下一次执行的时间戳
  private visible = !globalThis.document || document.visibilityState === 'visible';
  private rafHandle = 0;

  constructor(fn: () => void, ms: number) {
    this.callback = fn;
    this.interval = ms;
    this.init();
  }

  private init() {
    if (typeof Worker !== 'undefined' && globalThis.document) {
      // 内联 Worker 代码,避免跨域问题
      const code = `
        let id = 0;
        self.onmessage = e => {
          if (e.data === 'start') {
            id = setInterval(() => self.postMessage('tick'), ${this.interval});
          } else if (e.data === 'stop') {
            clearInterval(id);
          }
        };
      `;
      const blob = new Blob([code], { type: 'application/javascript' });
      this.worker = new Worker(URL.createObjectURL(blob));
      this.worker.onmessage = () => this.safeCallback();
      this.bindVisibility();
    }
    this.reset();
  }

  private bindVisibility() {
    const handler = () => {
      this.visible = document.visibilityState === 'visible';
      this.reset();
    };
    document.addEventListener('visibilitychange', handler);
    // 内存释放接口
    this.destroy = () => {
      document.removeEventListener('visibilitychange', handler);
      this.stop();
      this.worker?.terminate();
    };
  }

  private reset() {
    this.stop();
    this.last = performance.now();
    if (this.visible) {
      this.loopRAF();
    } else if (this.worker) {
      this.worker.postMessage('start');
    } else {
      // Node 或无 Worker 环境退化
      this.timerId = setInterval(() => this.safeCallback(), this.interval);
    }
  }

  private loopRAF() {
    const now = performance.now();
    if (now - this.last >= this.interval - 1) { // 1ms 容差
      this.safeCallback();
      this.last = now;
    }
    this.rafHandle = requestAnimationFrame(() => this.loopRAF());
  }

  private safeCallback() {
    try { this.callback(); } catch (e) {
      // 生产环境可上报日志
      console.error('[ReliableInterval]', e);
    }
  }

  private stop() {
    if (this.rafHandle) cancelAnimationFrame(this.rafHandle);
    if (this.timerId) clearInterval(this.timerId as any);
    if (this.worker) this.worker.postMessage('stop');
    this.timerId = null;
    this.rafHandle = 0;
  }

  // 暴露给外部手动销毁
  destroy = () => {};
}

/* ===== 使用示例 ===== */
const timer = new ReliableInterval(() => {
  console.log('可靠 tick', Date.now());
}, 1000);

// 页面生命周期外主动销毁
window.addEventListener('beforeunload', () => timer.destroy());

要点回顾

  1. 可见时 RAF 保证 60 FPS 对齐,隐藏时 Worker 保证精准,双通道无缝切换。
  2. 时间戳漂移在 RAF 分支内实时补偿,Worker 分支天然精准,无需额外逻辑。
  3. 异常被捕获,不影响后续 tick;destroy 方法一次性回收所有资源,防止闭包与 Worker 泄漏。
  4. Node 环境无 DOM 时自动退化为 setInterval,仍保留 try/catch 与时间戳监控,方便后续做“漂移告警”。

拓展思考

  1. 如果业务要求“绝对准点”,可再引入 performance.now() 做“追帧”策略:页面恢复后发现漏了 N 次,可选择一次性补齐或丢弃,需与产品确认。
  2. 小程序、WebView 可能屏蔽 Blob Worker,可降级到 setInterval + visibility 补偿,或让 Native 注入一个“定时器服务”通过 JSBridge 回调。
  3. 对于“倒计时”场景,建议把“剩余秒数”存在内存 + localStorage 双保险,防止页面被系统回收后重启对时错误。
  4. 若需“节流执行”而非“补齐执行”,可把回调改为“可重入”状态机,记录最新一次即可,避免雪崩。
  5. 在 Serverless 边缘函数里,没有 setInterval 也没有 RAF,可借助 Cron 触发器或边缘 KV 的“延迟消息”实现“类定时器”语义,把逻辑搬到调度层而非进程内。