比 setInterval 更精準,可動態調整間隔,避免執行時間導致的間隔偏移。
function startCounter() {
var seconds = 0;
var $display = $('#counter-display');
function tick() {
seconds++;
$display.text(seconds + ' 秒');
// 遞歸調用,形成循環
timerId = setTimeout(tick, 1000);
}
var timerId = setTimeout(tick, 1000); // 啟動
// 返回控制接口
return {
stop: function() { clearTimeout(timerId); },
getSeconds: function() { return seconds; }
};
}
// 使用
var counter = startCounter();
// 10 秒後停止
setTimeout(function() { counter.stop(); }, 10000);
class Timer {
constructor(interval = 1000) {
this.interval = interval;
this.elapsed = 0;
this.timerId = null;
this.startTime = null;
this.callback = null;
}
start(callback) {
this.callback = callback;
this.startTime = Date.now() - this.elapsed;
this._tick();
}
_tick() {
this.elapsed = Date.now() - this.startTime;
if (this.callback) this.callback(this.elapsed);
this.timerId = setTimeout(() => this._tick(), this.interval);
}
pause() {
if (this.timerId) {
clearTimeout(this.timerId);
this.timerId = null;
}
}
resume() {
if (!this.timerId) this._tick();
}
reset() {
this.pause();
this.elapsed = 0;
}
getFormattedTime() {
var ms = this.elapsed;
var s = Math.floor(ms / 1000) % 60;
var m = Math.floor(ms / 60000) % 60;
var h = Math.floor(ms / 3600000);
return (h ? h + ':' : '') +
(m < 10 ? '0' : '') + m + ':' +
(s < 10 ? '0' : '') + s;
}
}
// 使用示例
var timer = new Timer(100);
timer.start(function(elapsed) {
$('#display').text(timer.getFormattedTime());
});
// 暫停/繼續按鈕
$('#pause-btn').click(function() { timer.pause(); });
$('#resume-btn').click(function() { timer.resume(); });
$('#reset-btn').click(function() { timer.reset(); $('#display').text('00:00'); });
function Countdown(targetSeconds, options) {
var opts = $.extend({
onTick: null, // 每秒回調(剩餘秒數)
onEnd: null, // 結束回調
interval: 1000
}, options);
var remaining = targetSeconds;
var timerId = null;
function tick() {
if (remaining <= 0) {
clearTimeout(timerId);
if (opts.onEnd) opts.onEnd();
return;
}
if (opts.onTick) opts.onTick(remaining);
remaining--;
timerId = setTimeout(tick, opts.interval);
}
this.start = function() { tick(); };
this.stop = function() { clearTimeout(timerId); };
this.getRemaining = function() { return remaining; };
}
// 使用:60 秒倒計時
var cd = new Countdown(60, {
onTick: function(sec) {
$('#countdown').text(formatTime(sec));
},
onEnd: function() {
alert('時間到!');
$('#countdown').text('00:00');
}
});
cd.start();
function formatTime(sec) {
var m = Math.floor(sec / 60);
var s = sec % 60;
return (m < 10 ? '0' : '') + m + ':' + (s < 10 ? '0' : '') + s;
}
| 特性 | setTimeout 遞歸 | setInterval |
|---|---|---|
| 間隔精度 | 高(每次重新計算) | 低(固定排程,積累誤差) |
| 動態調整間隔 | 支持 | 需 clear+set 重建 |
| 執行時間超過間隔 | 順序執行,不重疊 | 可能並行/丟幀 |
| 內存洩漏風險 | 低(單一 timerId) | 高(易忘記 clearInterval) |
| 適用場景 | 動畫、倒計時、輪詢 | 固定頻率輪詢、心跳 |
頁面隱藏/最小化時,瀏覽器會將 setTimeout 間隔限制在 1000ms+。動畫類場景請改用 requestAnimationFrame:
function smoothAnimation() {
var start = performance.now();
function frame(now) {
var progress = Math.min((now - start) / 1000, 1); // 1秒動畫
updateUI(progress);
if (progress < 1) requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
}