javascript带有毫秒的计时器代码实例

快乐打工仔 分类:实例代码

分享一段代码实例,它实现了简单的计时器效果,并且带有毫秒功能。

外观比较粗陋,主要目的还是要学习它的实现方式和相关知识点。

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<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>

javascript带有毫秒的计时器代码实例,这样的场景在实际项目中还是用的比较多的,关于javascript带有毫秒的计时器代码实例就介绍到这了。

javascript带有毫秒的计时器代码实例属于前端实例代码,有关更多实例代码大家可以查看

回复

我来回复
  • 暂无回复内容