頁面實時時鐘是JavaScript入門經典案例。本文從傳統setTimeout遞歸實現演進到現代Intl.DateTimeFormat國際化格式化、requestAnimationFrame優化、Web Worker離屏計算,並解決「閏秒/夏令時/時區」等邊界問題。
<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規範),長時間運行會偏移秒級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);
}
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);
// 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();