javascript - javascript 中的秒表使用新的 Date 对象

标签 javascript

在下面的脚本中,我尝试制作某种秒表:

<html>
  <head>
   <script>
     var t; var time; var timetoRun=180000;// 3 min

     function Timer()
     {
      stoper = (this.startTime+ this.timetoRun)-new Date().getTime();
      x = parseInt(stoper / 1000);
      s = x % 60;
      x = parseInt(x/60);
      m = x % 60;
      if (s<10) s='0'+ s;document.getElementById('txt').innerHTML=m+':'+s; 
      this.t=setTimeout(function(){Timer()},500);
     }

    function myStopFunction(){clearTimeout(t);}
    function init(){this.startTime = new Date().getTime();}
   </script>
  </head>

   <body onload="init()">
     <div id="txt"></div>
     <button onclick="myStopFunction()">Stop time</button>
     <button onclick="Timer()">Start time</button>
   </body>
</html>

问题是:当我在2:28停止时间并在5秒后再次开始时。值立即跳转到 2:23 。我想要实现的是:将时间停止在(例如)2:31 并从 2:31 再次运行。

提前致谢。

最佳答案

您可以简化很多代码,以避免使用 Date 对象。

此外,您还忘记了一些 var 关键字和一个在时间用完时停止计时器的条件。我还插入了一个 resetTimer 方法,因此如果您需要重新启动计时器两次或更多次,它将再次设置为 180

代码笔示例:http://codepen.io/anon/pen/Duier

代码

      var 
         // seconds
         timetoRun,             
         // cache a reference to the DOM element in which you update the timer
         timeElement, 
         // your interval
         intv;

      function Timer() {
          var ss = timetoRun % 60;
          var mm = (timetoRun / 60) | 0;  // Math.floor

          if (ss < 10) ss = '0' + ss;
          timeElement.innerHTML = [mm,ss].join(":"); 

          if (timetoRun-- > 0) {
              intv = setTimeout(Timer, 1000);
          }
          else {
              myStopFunction();
              resetTimer();
          }
      };

      function myStopFunction() {  clearInterval(intv); };

      function resetTimer() {
         timetoRun = 180  //second;
      };

      function init() { 
         resetTimer(); 
         timeElement = document.getElementById('txt');
      };

关于javascript - javascript 中的秒表使用新的 Date 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21782369/

相关文章:

javascript - 动态移除最后一个 div

javascript - Youtube,该网站本身卡住了几秒钟

javascript - 在 PHP 中,我从 mySQL 编码了一个 JSON 数组。我想在不同的 php 文件中解码它

javascript - 如何消除div标签之间的垂直空间

javascript - jQuery 插件的 RequireJS shim 路径

javascript - React 中的表单提交

javascript - 传递选择器或对象,将其转换为 jQuery 对象的最佳方法是什么?

javascript - 如何从 Angular 路由中排除路由?

javascript - 如何在带有yield的生成器中使用Array.prototype.reduce?

javascript - 军用(24小时)和民用(23 :59) format)时间匹配的正则表达式