DIV CSS 佈局教程網

用 setTimeout 實作 JavaScript 計數器
編輯:關於JavaScript     

計數器是最典型的定時器練習:每隔一秒讓數字加一,並能隨時啟動與停止。以下範例用一個旗標避免重複啟動多個計時器。

範例

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 的取捨

這裡刻意用「setTimeout 遞迴」而非 setInterval,是有原因的:

  • 不會堆積:setInterval 到了時間就觸發,若回呼執行時間超過間隔,後面的呼叫會排隊等待,造成執行動作連續爆發。setTimeout 則是「做完再排下一次」,永遠不會堆疊。
  • 間隔可動態調整:每次遞迴時都能重新決定下一次的延遲。
  • 配合 requestAnimationFrame 做動畫:視覺類的計時應改用 rAF,它會與螢幕刷新同步,且在分頁隱藏時自動暫停,省電又順。

封裝成可重複使用的計數器

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(); };

把狀態閉鎖在閉包裡,外部只能透過方法操作,不必擔心全域變數被誤改。

兩個實務提醒

  1. 瀏覽器會節流背景分頁的計時器:分頁隱藏後,setTimeout 最小間隔可能被拉長到 1 秒甚至更久。若計時必須精準(例如倒數截止時間),請以 Date.now() 的差值計算,而不是累加次數。
  2. 用 performance.now() 而非 Date 計量耗時:前者是單調遞增的高解析度時鐘,不會因系統時間調整而跳動,更適合量測間隔。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved