萬盛學電腦網

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

JavaScript 停止 setInterval 與 setTimeout 計時器完整指南

在 JavaScript 中,setInterval 與 setTimeout 是處理非同步重複執行與延遲執行的核心 API。但許多開發者忽略了如何正確停止它們,導致記憶體洩漏或邏輯錯誤。本文詳細說明 clearInterval 與 clearTimeout 的正確用法、參數意義與實務範例。

一、setInterval 週期性執行與停止

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 延遲單次執行與停止

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秒後繼續

總結

  • 永遠保存計時器 ID:const id = setInterval(fn, ms)
  • 對應停止:clearInterval(id) / clearTimeout(id)
  • 避免字串參數:直接傳遞函式參考
  • 清理機制:元件銷毀時(如 Vue beforeUnmount、React useEffect cleanup)務必清除所有計時器
copyright © 萬盛學電腦網 all rights reserved