萬盛學電腦網

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

JavaScript 實現數字時鐘:Date 對象與定時器實戰

核心邏輯

function Format2Len(i) {
    return i < 10 ? "0" + i : i; // 單位數補零
}

function RefreshClock() {
    var CurrentTime = new Date();
    var timeStr = CurrentTime.getFullYear() + "-" +
                  Format2Len(CurrentTime.getMonth() + 1) + "-" +
                  Format2Len(CurrentTime.getDate()) + " " +
                  Format2Len(CurrentTime.getHours()) + ":" +
                  Format2Len(CurrentTime.getMinutes()) + ":" +
                  Format2Len(CurrentTime.getSeconds());
    txtClock.value = timeStr;
}

setInterval("RefreshClock()", 1000); // 每秒更新

Date 關鍵方法表

方法返回值注意
getFullYear()四位年份
getMonth()0-11需 +1 得到實際月份
getDate()1-31當月日期
getHours()0-2324小時制
getMinutes()0-59
getSeconds()0-59

三元運算符優化補零

// 等價於
if (i < 10) { return "0" + i; } else { return i; }

簡潔且無副作用,適合格式化數字。

HTML 掛載

<body onload="RefreshClock()">
  當前時間:<input type="text" id="txtClock" />
</body>

onload 確保頁面載入即顯示時間,setInterval 後續每秒刷新。

現代化改進

  • 使用 toLocaleTimeString() / toLocaleDateString() 自動本地化格式。
  • Intl.DateTimeFormat 精確控制輸出格式。
  • requestAnimationFrame 配合 performance.now() 減少定時器誤差。
  • Web Worker 將計時邏輯移出主線程。

完整可運行示例

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>數字時鐘</title></head>
<body>
  <div id="clock" style="font: 24px monospace;"></div>
  <script>
    const el = document.getElementById('clock');
    function update() {
      const now = new Date();
      el.textContent = now.toLocaleTimeString('zh-CN', { hour12: false });
    }
    update();
    setInterval(update, 1000);
  </script>
</body></html>
copyright © 萬盛學電腦網 all rights reserved