計數器是最典型的定時器練習:每隔一秒讓數字加一,並能隨時啟動與停止。以下範例用一個旗標避免重複啟動多個計時器。
var count = 0;
var timer;
var timerOn = false;
function timedCount() {
count++;
timer = setTimeout(function () {
timedCount();
}, 1000);
}
function doTimer() {
if (!timerOn) {
timerOn = true;
timedCount();
}
}
function stopCount() {
clearTimeout(timer);
timerOn = false;
}
doTimer() 檢查 timerOn 旗標,若尚未啟動才呼叫 timedCount();timedCount() 讓 count 加一後,用 setTimeout 安排一秒後再呼叫自己,形成鏈式遞迴;stopCount() 則清除計時器並把旗標復位。
旗標的作用是防止使用者連點「開始」導致好幾條計時鏈同時跑,count 也會莫名跳得飛快。
這裡刻意用「setTimeout 遞迴」而非 setInterval,是有原因的:
setInterval 到了時間就觸發,若回呼執行時間超過間隔,後面的呼叫會排隊等待,造成執行動作連續爆發。setTimeout 則是「做完再排下一次」,永遠不會堆疊。
function createCounter(interval, onTick) {
var timer = null;
var count = 0;
function loop() {
count++;
onTick(count);
timer = setTimeout(loop, interval);
}
return {
start: function () {
if (timer !== null) return; // 已在執行,避免重複啟動
loop();
},
stop: function () {
clearTimeout(timer);
timer = null;
},
reset: function () {
this.stop();
count = 0;
onTick(count);
},
getCount: function () { return count; }
};
}
// 使用
var el = document.getElementById('counter');
var c = createCounter(1000, function (n) { el.textContent = n; });
document.getElementById('start').onclick = function () { c.start(); };
document.getElementById('stop').onclick = function () { c.stop(); };
document.getElementById('reset').onclick = function () { c.reset(); };
把狀態閉鎖在閉包裡,外部只能透過方法操作,不必擔心全域變數被誤改。
Date.now() 的差值計算,而不是累加次數。