在 JavaScript 中,setInterval 與 setTimeout 是處理非同步重複執行與延遲執行的核心 API。但許多開發者忽略了如何正確停止它們,導致記憶體洩漏或邏輯錯誤。本文詳細說明 clearInterval 與 clearTimeout 的正確用法、參數意義與實務範例。
setInterval 依指定週期(毫秒)重複呼叫函式,回傳一個唯一的計時器 ID(整數),必須保存此 ID 才能稍後透過 clearInterval 停止。
var timerId = setInterval(callback, delayMs);
// 停止
clearInterval(timerId);
<input type="text" id="clock" size="50" />
<button onclick="stopClock()">停止計時</button>
<script>
var intervalId = setInterval(clock, 50); // 每 50ms 更新一次
function clock() {
var now = new Date();
document.getElementById("clock").value = now.toLocaleTimeString();
}
function stopClock() {
clearInterval(intervalId); // 必須使用 setInterval 回傳的 ID
console.log("計時器已停止");
}
</script>
setTimeout 在指定毫秒後執行一次函式,同樣回傳計時器 ID,透過 clearTimeout 取消尚未執行的排程。
var timeoutId = setTimeout(callback, delayMs);
// 取消
clearTimeout(timeoutId);
<input type="button" value="開始計數" onclick="startCount()">
<input type="text" id="txt" />
<input type="button" value="停止計數" onclick="stopCount()">
<script>
var c = 0;
var timeoutId;
function timedCount() {
document.getElementById('txt').value = c;
c++;
timeoutId = setTimeout(timedCount, 1000); // 遞迴排程,每秒執行一次
}
function startCount() {
if (!timeoutId) timedCount(); // 防止重複啟動
}
function stopCount() {
clearTimeout(timeoutId);
timeoutId = null; // 重置狀態
}
</script>
| 錯誤寫法 | 問題 | 正確做法 |
|---|---|---|
setInterval("clock()", 50) 字串形式 |
隱含 eval,效能差、安全風險、作用域混亂 |
setInterval(clock, 50) 直接傳函式參考 |
未保存回傳 ID 直接呼叫 clearInterval() |
無法停止特定計時器 | 宣告變數 var id = setInterval(...) |
在迴圈中重複呼叫 setInterval 未清除舊的 |
產生多個平行計時器,導致回調頻率倍增 | 啟動前檢查 if (!timerId) 或先 clearInterval |
setTimeout 回調中未重新賦值 timeoutId |
遞迴排程時無法正確取消後續排程 | 回調內重新賦值:timeoutId = setTimeout(...) |
class PausableTimer {
constructor(callback, delay) {
this.callback = callback;
this.delay = delay;
this.timerId = null;
this.remaining = delay;
this.startTime = 0;
}
start() {
if (this.timerId) return;
this.startTime = Date.now();
this.timerId = setTimeout(() => {
this.timerId = null;
this.callback();
if (this.remaining > 0) this.start(); // 循環模式
}, this.remaining);
}
pause() {
if (!this.timerId) return;
clearTimeout(this.timerId);
this.remaining -= Date.now() - this.startTime;
this.timerId = null;
}
resume() {
if (this.remaining <= 0) return;
this.start();
}
stop() {
if (this.timerId) clearTimeout(this.timerId);
this.timerId = null;
this.remaining = this.delay;
}
}
// 使用
const timer = new PausableTimer(() => console.log('tick'), 1000);
timer.start();
setTimeout(() => timer.pause(), 3500); // 3.5秒後暫停
setTimeout(() => timer.resume(), 5500); // 2秒後繼續
const id = setInterval(fn, ms)clearInterval(id) / clearTimeout(id)beforeUnmount、React useEffect cleanup)務必清除所有計時器