萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 定時器完全指南:setTimeout/setInterval、遞歸模式、請求動畫幀與最佳實踐

核心 API 對比

API執行模式返回值取消方法典型用途
setTimeout(fn, delay)單次延遲執行timerIdclearTimeout(id)延遲執行、防抖、遞歸循環
setInterval(fn, interval)固定間隔重複執行timerIdclearInterval(id)輪詢、心跳、簡單動畫
requestAnimationFrame(fn)下一幀執行(~16.7ms)requestIdcancelAnimationFrame(id)高性能動畫、視覺更新
requestIdleCallback(fn)瀏覽器空閒期執行idleIdcancelIdleCallback(id)非緊急計算、數據預處理

setTimeout 遞歸 vs setInterval


// ❌ setInterval 缺陷:執行時間長導致間隔壓縮、錯過幀、無法動態調整間隔
setInterval(() => {
  heavyTask(); // 耗時 100ms
}, 100); // 實際間隔 < 100ms,甚至並行執行

// ✅ setTimeout 遞歸:每次執行完才排程下一次,間隔精確可控
function loop() {
  heavyTask();
  timerId = setTimeout(loop, 100); // 動態調整:setTimeout(loop, dynamicInterval)
}
loop();

// ✅ 請求動畫幀:與瀏覽器刷新同步,適合視覺動畫
function animate() {
  updatePosition();
  requestAnimationFrame(animate);
}
requestAnimationFrame(animate);

可控制的定時器類封裝


class Timer {
  constructor(fn, delay, options = {}) {
    this.fn = fn;
    this.delay = delay;
    this.options = Object.assign({
      immediate: false,  // 立即執行一次
      maxRuns: Infinity, // 最大執行次數
      context: null,     // this 綁定
      args: []           // 預設參數
    }, options);
    
    this.timerId = null;
    this.runCount = 0;
    this.running = false;
  }
  
  start() {
    if (this.running) return this;
    this.running = true;
    if (this.options.immediate) this._execute();
    this._schedule();
    return this;
  }
  
  _schedule() {
    if (!this.running || this.runCount >= this.options.maxRuns) return;
    this.timerId = setTimeout(() => this._execute(), this.delay);
  }
  
  _execute() {
    if (!this.running) return;
    this.runCount++;
    this.fn.apply(this.options.context, this.options.args);
    this._schedule();
  }
  
  stop() {
    this.running = false;
    if (this.timerId) clearTimeout(this.timerId);
    this.timerId = null;
    return this;
  }
  
  pause() { return this.stop(); }
  resume() { return this.start(); }
  
  setDelay(delay) {
    this.delay = delay;
    if (this.running) { this.stop(); this.start(); }
    return this;
  }
  
  getRunCount() { return this.runCount; }
}

// 使用
const timer = new Timer(() => console.log('tick'), 1000, { immediate: true, maxRuns: 5 })
  .start();

// 動態調整
setTimeout(() => timer.setDelay(500), 3000);

實戰場景模式

1. 防抖


function debounce(fn, delay) {
  let timer = null;
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

// 輸入框搜索建議
const search = debounce(query => fetchSuggestions(query), 300);
input.addEventListener('input', e => search(e.target.value));

2. 節流


function throttle(fn, interval) {
  let last = 0;
  return function(...args) {
    const now = Date.now();
    if (now - last >= interval) {
      last = now;
      fn.apply(this, args);
    }
  };
}

// 滾動事件節流
window.addEventListener('scroll', throttle(() => {
  checkVisibility();
}, 100));

3. 輪詢與退避重試


function poll(conditionFn, options = {}) {
  const { interval = 1000, maxRetries = 30, backoff = 1 } = options;
  let retries = 0;
  
  return new Promise((resolve, reject) => {
    function check() {
      if (conditionFn()) return resolve(true);
      if (++retries >= maxRetries) return reject(new Error('Poll timeout'));
      
      const delay = interval * Math.pow(backoff, retries - 1);
      setTimeout(check, delay);
    }
    check();
  });
}

// 使用:等待元素出現
poll(() => document.getElementById('target'), { interval: 100, maxRetries: 50 })
  .then(el => console.log('元素就緒', el));

4. 動畫循環 (requestAnimationFrame)


class AnimationLoop {
  constructor(update, render) {
    this.update = update;
    this.render = render;
    this.running = false;
    this.lastTime = 0;
  }
  
  start() {
    if (this.running) return;
    this.running = true;
    this.lastTime = performance.now();
    this._tick();
  }
  
  _tick() {
    if (!this.running) return;
    const now = performance.now();
    const delta = (now - this.lastTime) / 1000; // 秒
    this.lastTime = now;
    
    this.update(delta);
    this.render();
    requestAnimationFrame(() => this._tick());
  }
  
  stop() { this.running = false; }
}

// 使用
const loop = new AnimationLoop(
  dt => { player.x += player.vx * dt; }, // 更新邏輯
  () => { ctx.clearRect(0,0,w,h); drawPlayer(); } // 渲染
).start();

定時器精度與瀏覽器節流

場景最小間隔說明
前台頁面4ms (HTML5 標準)setTimeout/setInterval 最小夾縫
後台標籤頁1000ms (大多數瀏覽器)節省資源,定時器大幅延遲
無痕/省電模式更高/不可靠可能完全暫停
Web Worker無限制獨立線程,不受主線程節流影響

後台運行解決方案


// 1. Web Worker 運行定時任務
// worker.js
setInterval(() => postMessage('tick'), 1000);

// main.js
const worker = new Worker('worker.js');
worker.onmessage = e => console.log(e.data);

// 2. Page Visibility API 配合
let timerId;
document.addEventListener('visibilitychange', () => {
  if (document.hidden) {
    clearInterval(timerId);
  } else {
    timerId = setInterval(doWork, 1000);
  }
});

// 3. Service Worker 定時同步 (離線/後台)
self.addEventListener('periodicsync', e => {
  if (e.tag === 'sync-data') e.waitUntil(syncData());
});

內存洩漏防範

  1. 組件銷毀時 必須清理 所有 timerId
  2. 使用 WeakMap 管理實例與定時器關聯,避免循環引用
  3. 避免在循環/高頻調用中創建閉包捕獲大對象
  4. React/Vue 中用 useEffect/onUnmounted 統一清理

// React Hook 封裝
function useTimer(fn, delay, deps = []) {
  const saved = useRef(fn);
  useEffect(() => { saved.current = fn; }, [fn]);
  
  useEffect(() => {
    if (!delay) return;
    const id = setInterval(() => saved.current(), delay);
    return () => clearInterval(id);
  }, [delay, ...deps]);
}
copyright © 萬盛學電腦網 all rights reserved