萬盛學電腦網

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

JavaScript/jQuery 定時器三大實作模式:setInterval、遞迴 setTimeout、手動啟停控制

模式一:setInterval 固定間隔(簡單但風險較高)

$(function() {
  setInterval(function() {
    $('#currentTime').text(new Date().toLocaleString());
  }, 1000);
});

缺點:若回呼執行時間 > 間隔,會導致佇列堆疊;無法動態調整間隔或優雅停止。

模式二:遞迴 setTimeout(推薦)

function startClock() {
  $('#currentTime').text(new Date().toLocaleString());
  clockTimer = setTimeout(startClock, 1000); // 遞迴排程下一次
}
$(function() { startClock(); });

// 停止
function stopClock() { clearTimeout(clockTimer); }

優點:每次執行完才排程下一次,天然避免堆疊;可在回呼內動態決定是否繼續、調整間隔。

模式三:手動啟停計數器(教學經典)

var counter = 0, timerId;
function tick() {
  document.getElementById('txt').value = counter++;
  timerId = setTimeout(tick, 1000);
}
function stop() { clearTimeout(timerId); }

// HTML
<input type="button" value="開始" onclick="tick()">
<input type="text" id="txt">
<input type="button" value="停止" onclick="stop()">

進階:封裝可複用 Timer 類別

class Timer {
  constructor(callback, interval) {
    this.callback = callback;
    this.interval = interval;
    this.timerId = null;
    this.running = false;
  }
  start() {
    if (this.running) return;
    this.running = true;
    this._tick();
  }
  stop() {
    this.running = false;
    clearTimeout(this.timerId);
  }
  _tick() {
    if (!this.running) return;
    this.callback();
    this.timerId = setTimeout(() => this._tick(), this.interval);
  }
  setInterval(ms) { this.interval = ms; }
}

// 使用
const clock = new Timer(() => $('#time').text(new Date().toLocaleTimeString()), 1000);
clock.start();
// clock.stop(); clock.setInterval(2000);

請求動畫幀:高精度動畫專用

function animate() {
  // 60fps 約 16.67ms
  requestAnimationFrame(animate);
}
// 僅用於視覺動畫,不適用於邏輯定時
copyright © 萬盛學電腦網 all rights reserved