萬盛學電腦網

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

JavaScript 計時器完整實作指南:setTimeout/setInterval 巢狀調用、記憶體釋放與最佳實踐

基礎 API 速查

方法用途回傳值清除方法
setTimeout(fn, delay)延遲一次性執行Timer ID (number)clearTimeout(id)
setInterval(fn, interval)週期性重複執行Timer ID (number)clearInterval(id)
requestAnimationFrame(fn)下一幀執行(動畫專用)Request IDcancelAnimationFrame(id)

完整可執行範例:即時時鐘


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS 計時器 Demo</title>
</head>
<body>
  <input type="text" id="current_time" readonly style="width:220px;font-family:monospace;" />
  <button onclick="startClock()">開始</button>
  <button onclick="stopClock()">停止</button>

  <script>
    var timerId = null;

    function updateClock() {
      var d = new Date();
      var pad = function(n) { return (n < 10 ? '0' : '') + n; };
      var timeStr = d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) + ' ' +
                    pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds());
      document.getElementById('current_time').value = timeStr;
    }

    function startClock() {
      if (timerId) return; // 防止重複啟動
      updateClock();       // 立即顯示一次
      timerId = setInterval(updateClock, 1000);
    }

    function stopClock() {
      if (timerId) {
        clearInterval(timerId);
        timerId = null;
      }
    }

    // 頁面卸載時自動清理(防記憶體洩漏)
    window.addEventListener('beforeunload', stopClock);
  </script>
</body>
</html>

巢狀調用模式:遞迴 setTimeout 替代 setInterval


function repeatWithDelay(fn, delay) {
  var timerId = null;
  function loop() {
    fn();
    timerId = setTimeout(loop, delay); // 執行完才排程下一次
  }
  loop();
  return {
    stop: function() { clearTimeout(timerId); }
  };
}

// 使用:確保前一次執行完成才開始計時,避免長任務堆疊
var clock = repeatWithDelay(updateClock, 1000);
// clock.stop() 可隨時停止

優點:動態調整間隔、避免執行時間超過間隔導致並發、錯誤不會中斷後續排程。

常見坑點與解決方案

問題原因解決
setInterval 卡頓、時間漂移主執行緒忙碌、回呼執行時間 > 間隔改用遞迴 setTimeout 或 requestAnimationFrame
this 指向錯誤setTimeout(obj.method, 1000) 導致 this 丟失setTimeout(obj.method.bind(obj), 1000) 或箭頭函式
元件銷毀後計時器殘留未在 unmount/beforeunload 清除統一管理 timerId,生命週期結束時清理
大量計時器效能問題數百個 setInterval 佔用主執行緒合併為單一計時器 + 任務隊列、或用 Web Worker

進階:可暫停/繼續/動態調速的計時器類別


class SmartTimer {
  constructor(fn, interval) {
    this.fn = fn;
    this.interval = interval;
    this.timerId = null;
    this.remaining = interval;
    this.lastTick = 0;
    this.running = false;
  }

  start() {
    if (this.running) return;
    this.running = true;
    this.lastTick = Date.now();
    this.timerId = setTimeout(this._tick.bind(this), this.remaining);
  }

  pause() {
    if (!this.running) return;
    clearTimeout(this.timerId);
    this.remaining -= Date.now() - this.lastTick;
    this.running = false;
  }

  resume() {
    if (this.running) return;
    this.start();
  }

  setInterval(ms) {
    this.interval = ms;
    if (this.running) {
      this.pause();
      this.resume();
    }
  }

  _tick() {
    this.fn();
    if (this.running) {
      this.lastTick = Date.now();
      this.timerId = setTimeout(this._tick.bind(this), this.interval);
    }
  }

  destroy() {
    this.pause();
    this.fn = null;
  }
}

結語

掌握 setTimeout 遞迴模式、clearTimeout/clearInterval 生命週期管理、this 綁定技巧與進階類別封裝,即能打造穩定、可控、無記憶體洩漏的計時器系統。

copyright © 萬盛學電腦網 all rights reserved