DIV CSS 佈局教程網

純 JavaScript 實作網頁即時時鐘
編輯:JavaScript綜合知識     

要在網頁上顯示一個每秒跳動的時間,不需要任何外掛,只要 Date 物件加上 setTimeout 的循環即可。

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>即時時鐘</title>
<script language="javascript">
  var t = null;

  function time() {
    clearTimeout(t);                    // 先清掉舊的計時器,避免堆疊
    var dt = new Date();
    var h = dt.getHours();
    var m = dt.getMinutes();
    var s = dt.getSeconds();
    document.getElementById("timeShow").innerHTML =
      "現在的時間為:" + h + "時" + m + "分" + s + "秒";
    t = setTimeout(time, 1000);         // 排下一輪
  }

  window.onload = function () {
    t = setTimeout(time, 1000);         // 啟動
  };
</script>
</head>
<body>
  <label id="timeShow"></label>
</body>
</html>

幾個值得改進的地方

補零:直接輸出 getMinutes() 會出現「9 分」而非「09 分」,時鐘看起來會怪。加一個小工具函式即可:

function pad(n) { return n < 10 ? "0" + n : "" + n; }
// 使用:pad(h) + "時" + pad(m) + "分" + pad(s) + "秒"

用 setInterval 更省事:既然只是重複同一件事,用 setInterval(time, 1000) 就不需要手動排下一輪與清除:

var timer = setInterval(time, 1000);
// 停止時:clearInterval(timer);

對齊真實秒數:setTimeout 有累積誤差,長時間執行會慢慢落後。若在意精準度,可改成依「距離下一整秒還剩幾毫秒」動態計算延遲,或使用 Date#toLocaleTimeString() 直接交給瀏覽器格式化。

另外提醒:原範例把 setTimeout 寫在 script 頂端,那時 timeShow 這個元素可能還沒被解析到。把啟動動作移到 window.onload(或把 script 放到 body 尾端)是比較穩妥的作法。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved