基本模式
var count = 0, timer = null, timerOn = false;
function timedCount() {
count++;
timer = setTimeout(timedCount, 1000); // 遞迴排程下一秒
}
function startTimer() {
if (!timerOn) { timerOn = true; timedCount(); }
}
function stopTimer() {
clearTimeout(timer);
timerOn = false;
}
關鍵點解析
- 遞迴 setTimeout vs setInterval:
setTimeout 遞迴確保每次回呼執行完畢後再排程下一次,間隔精確等於「執行時間 + 1000ms」;setInterval 無視執行時間,若回呼耗時長會導致疊加或跳幀。
- 狀態旗標:
timerOn 防止重複啟動;timer 保存 ID 供 clearTimeout 使用。
- 閉包改寫:將狀態封裝於函式內部,避免全域變數汙染。
進階:可複用計數器類別
class Counter {
constructor(interval = 1000) { this.interval = interval; this.count = 0; this.timer = null; }
start() { if (this.timer) return; this.tick(); }
tick() { this.count++; this.timer = setTimeout(() => this.tick(), this.interval); }
stop() { clearTimeout(this.timer); this.timer = null; }
reset() { this.stop(); this.count = 0; }
getValue() { return this.count; }
}
// 使用
const c = new Counter(1000);
c.start();
// 5秒後
setTimeout(() => { console.log(c.getValue()); c.stop(); }, 5000);
應用場景
- 倒數計時器(結合
Date.now() 計算剩餘時間)
- 定期輪詢 API(需加入錯誤重試、指數退避)
- 動畫幀計數、效能監控(FPS 計算)
注意事項
- 分頁切換至背景時,瀏覽器會降低
setTimeout 頻率(最低 1 秒),計數會變慢。
- 若需高精度計時,請使用
Date.now() 記錄起始時間,每幀計算差值,而非依賴遞迴次數。
- 清理時務必
clearTimeout,否則記憶體洩漏且邏輯錯誤。