萬盛學電腦網

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

JavaScript實時顯示當前時間:setTimeout遞歸與現代Intl.DateTimeFormat方案

頁面實時時鐘是JavaScript入門經典案例。本文從傳統setTimeout遞歸實現演進到現代Intl.DateTimeFormat國際化格式化、requestAnimationFrame優化、Web Worker離屏計算,並解決「閏秒/夏令時/時區」等邊界問題。

傳統實現:setTimeout 遞歸

<div id="clock"></div>
<script>
function showTime() {
    var now = new Date();
    var year = now.getFullYear();
    var month = String(now.getMonth() + 1).padStart(2, '0');
    var day = String(now.getDate()).padStart(2, '0');
    var hour = String(now.getHours()).padStart(2, '0');
    var min = String(now.getMinutes()).padStart(2, '0');
    var sec = String(now.getSeconds()).padStart(2, '0');
    var week = ['日','一','二','三','四','五','六'][now.getDay()];
    
    document.getElementById('clock').textContent = 
        year + '年' + month + '月' + day + '日 星期' + week + ' ' + hour + ':' + min + ':' + sec;
    
    setTimeout(showTime, 1000); // 遞歸調度
}
showTime();

缺陷分析

  • 誤差累積:setTimeout最小延遲4ms(HTML5規範),長時間運行會偏移秒級
  • 主線程阻塞:重計算/重排可能延遲回調執行
  • 格式化硬編碼:多語言/時區適配困難

現代方案一:Intl.DateTimeFormat (國際化標準)

const formatter = new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit',
    hour12: false, weekday: 'long'
});

function updateClock() {
    document.getElementById('clock').textContent = formatter.format(new Date());
    setTimeout(updateClock, 1000);
}

現代方案二:requestAnimationFrame + 僅秒變化時更新

let lastSec = -1;
function tick(timestamp) {
    const now = new Date();
    const sec = now.getSeconds();
    if (sec !== lastSec) {
        lastSec = sec;
        document.getElementById('clock').textContent = formatter.format(now);
    }
    requestAnimationFrame(tick);
}
requestAnimationFrame(tick);

現代方案三:Web Worker 離屏計算 (不阻塞主線程)

// clock-worker.js
setInterval(() => postMessage(new Date().toISOString()), 1000);

// 主線程
const worker = new Worker('clock-worker.js');
worker.onmessage = e => {
    document.getElementById('clock').textContent = new Date(e.data).toLocaleString('zh-CN');
};

時區與夏令時處理

// 顯示用戶本地時間 (默認)
new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });

// 固定時區 (服務端時間)
new Date(serverTimestamp).toLocaleString('zh-CN', { timeZone: 'UTC' });

// 獲取時區偏移
const offset = -new Date().getTimezoneOffset(); // 分鐘
const sign = offset >= 0 ? '+' : '-';
const tzStr = `UTC${sign}${String(Math.abs(offset)/60).padStart(2,'0')}:${String(Math.abs(offset)%60).padStart(2,'0')}`;

生產級組件封裝

class Clock {
    constructor(element, options = {}) {
        this.el = element;
        this.locale = options.locale || 'zh-CN';
        this.timeZone = options.timeZone; // undefined = 本地
        this.formatter = new Intl.DateTimeFormat(this.locale, {
            year: 'numeric', month: '2-digit', day: '2-digit',
            hour: '2-digit', minute: '2-digit', second: '2-digit',
            hour12: false, weekday: 'short', timeZone: this.timeZone
        });
        this.rafId = null;
        this.lastSec = -1;
    }
    
    start() {
        const tick = () => {
            const now = new Date();
            if (now.getSeconds() !== this.lastSec) {
                this.lastSec = now.getSeconds();
                this.el.textContent = this.formatter.format(now);
            }
            this.rafId = requestAnimationFrame(tick);
        };
        this.rafId = requestAnimationFrame(tick);
    }
    
    stop() { cancelAnimationFrame(this.rafId); }
    
    destroy() { this.stop(); this.el = null; }
}

// 使用
const clock = new Clock(document.getElementById('clock'), { timeZone: 'Asia/Shanghai' });
clock.start();
copyright © 萬盛學電腦網 all rights reserved