Implementation code of javascript stopwatch timer

  • 2021-08-03 08:36:46
  • OfStack

javascript Stopwatch Timer

Example code:


<html lang="en">
<head>
<meta charset="UTF-8">
<title>js Timer </title>
</head>
<body>
<input type="text" value="00:00">
<input type="button" value=" Begin ">
<input type="button" value=" End ">
<input type="button" value=" Reset ">
<script>

  var oTxt=document.getElementsByTagName("input")[0];
  var oStart=document.getElementsByTagName("input")[1];
  var oStop=document.getElementsByTagName("input")[2];
  var oReset=document.getElementsByTagName("input")[3];
  var n= 0, timer=null;
  // Start timing 
  oStart.onclick= function () {
    clearInterval(timer);
    timer=setInterval(function () {
      n++;
      var m=parseInt(n/60);
      var s=parseInt(n%60);
      oTxt.value=toDub(m)+":"+toDub(s);
    },1000/60);
  };
  // Pause and empty the timer 
  oStop.onclick= function () {
    clearInterval(timer);
  }
  // Reset 
  oReset.onclick= function () {
    oTxt.value="00:00";
    n=0;
  }
  // Zero-filling 
  function toDub(n){
    return n<10?"0"+n:""+n;
  }
</script>
</body>
</html>

In the timer setting running interval, 1 starts to set 100, which is actually wrong, because 1 second = 1000 milliseconds; We have to divide it into 60 numbers, so we have to divide it by 60.

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: