$(function() {
setInterval(function() {
$('#currentTime').text(new Date().toLocaleString());
}, 1000);
});
缺點:若回呼執行時間 > 間隔,會導致佇列堆疊;無法動態調整間隔或優雅停止。
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()">
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);
}
// 僅用於視覺動畫,不適用於邏輯定時