| 方法 | 用途 | 回傳值 | 清除方法 |
|---|---|---|---|
setTimeout(fn, delay) | 延遲一次性執行 | Timer ID (number) | clearTimeout(id) |
setInterval(fn, interval) | 週期性重複執行 | Timer ID (number) | clearInterval(id) |
requestAnimationFrame(fn) | 下一幀執行(動畫專用) | Request ID | cancelAnimationFrame(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>
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 綁定技巧與進階類別封裝,即能打造穩定、可控、無記憶體洩漏的計時器系統。