javascript帶有毫秒的計時器程式碼例項

antzone發表於2017-04-13

分享一段程式碼例項,它實現了簡單的計時器效果,並且帶有毫秒功能。

外觀比較粗陋,主要目的還是要學習它的實現方式和相關知識點。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script>
window.onload = function () {
  var child = document.getElementById('datetime').getElementsByTagName('span');
  var ostart = document.getElementById("start");
  var opause = document.getElementById("pause");
  var oreset = document.getElementById("reset");
  ostart.onclick = function () { startTime() }
  opause.onclick = function () { stopTime() }
  oreset.onclick = function () { resetTime() }
  var timer;
  var t = 0
  function Time() {
    var hours = child.item(0).innerHTML
    var minute = child.item(1).innerHTML
    var second = child.item(2).innerHTML
    var milliscond = child.item(3).innerHTML
    if (milliscond > 98) {
      if (second < 9) {
        child.item(2).innerHTML = '0' + (parseInt(second) + 1)
      } else {
        child.item(2).innerHTML = parseInt(second) + 1
      }
      if (second > 59) {
        if (minute < 9) {
          child.item(1).innerHTML = '0' + (parseInt(minute) + 1)
        } else {
          child.item(1).innerHTML = parseInt(minute) + 1
        }
        if (minute > 58) {
          if (hours < 9) {
            child.item(0).innerHTML = '0' + (parseInt(hours) + 1)
          } else {
            child.item(0).innerHTML = parseInt(hours) + 1
          }
          child.item(1).innerHTML = '00'
        }
        child.item(2).innerHTML = '00'
      }
      child.item(3).innerHTML = 00
      t = 0
    }
    else {
      t++
      if (t < 10 && milliscond < 10) {
        child.item(3).innerHTML = '0' + t
      } else {
        child.item(3).innerHTML = t
      }
    }
  }
  function startTime() {
    timer = setInterval(Time, 10);
  }
  function stopTime() {
    clearInterval(timer)
  }
  function resetTime() {
    var odiv = document.getElementById('datetime');
    odiv.innerHTML = "<span>00</span>:<span>00</span>:<span>00</span>:<span>00</span>";
  }
}
</script>
</head>
<body>
<button id="start">開始計時</button>
<button id="pause">暫停計時</button>
<button id="reset">重置計時</button>
<div id="datetime">
  <span>00</span>:
  <span>00</span>:
  <span>00</span>:
  <span>00</span>
</div>
</body>
</html>

相關文章