<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Document</title>

<style>

  #div1{

    width: 220px;

     height: 300px;

    background: gray;

    margin: 100px auto;

    border: 1px solid red;

    text-align: center

  }

#div1 div{

  background: orange;

  width: 220px;

  height: 50px;

  margin: 40px auto;

  text-align: center;

  line-height: 50px;

  font-size: 24px;

  color:white;

  }

 

#div1 button{

  width: 80px;

  height: 30px;

  margin: 5px;

  font-size: 15px;

  color: orange;

  }

</style>

</head>

<body>

  <div id = "div1">

    <div id="time"></div>

    <button onclick = "startClick();">开始</button><br />

    <button onclick = "pauseClick();">暂停</button><br />

    <button onclick = "stopClick();">重置</button>

  </div>

</body>

</html>

 

<script>

  var oTime = document.getElementById("time");

  oTime.innerHTML = "00:00:00:000";

  var h=0,m=0,s=0,t=0,timer=null;

   function startClick(){

    clearInterval(timer);//先去掉上一次的定时器,以防止连续按两次及以上的开始出现速度越来越快的情况,因为开了多个定时器

    timer = setInterval(function(){

      t= Number(t)+10;

       if(t>=1000){

          s++;

          t = 0;

        }

 

      if(s>60){

          m++;

          s = 0;

      }

 

      if(m>60){

         h++;

         m = 0;

      }

 

      if(t<10){

        t = "00"+t;

      }else if(t<100){

         t = "0"+t;

      }

 

      console.log(t)

      oTime.innerHTML = bZero(h)+":"+bZero(m)+":"+bZero(s)+":"+t;

  },10)

}

 

 

function pauseClick(){

  clearInterval(timer);

}

 

function stopClick(){

  clearInterval(timer);

  oTime.innerHTML = "00:00:00:000";

  h=0,m=0,s=0,t=0

}

 

 

function bZero(n){

  if(n<10){

  return "0"+n;

}

 

return n;

}

 

 

 

</script>

 

posted on 2018-08-16 20:53  薛小白  阅读(292)  评论(0编辑  收藏  举报