javascript - 为计时器添加开始、停止和重置按钮

标签 javascript

我正在制作一个计时器并让它已经工作了一个负载。我想给它添加一个开始、停止和重置按钮。这是我的代码和 atm。

    (function() {
         "use strict";
         var secondsLabel = document.getElementById('seconds'),
         minutesLabel = document.getElementById('minutes'),
         hoursLabel = document.getElementById('hours'),
         totalSeconds = 0,
         startButton = document.getElementById('start'),
         resetButton = document.getElementById('reset'),
         onOff = 0; 
         startButton.onclick = function() {
         onOff = 1;
     };
     resetButton.onclick = function() {
         totalSeconds = 0;
         onOff = 0;
     };

     if ( onOff == 1 ) {
         setInterval( setTime, 1000 );
         function setTime() {
         totalSeconds++;
         secondsLabel.innerHTML = pad( totalSeconds % 60 );
         minutesLabel.innerHTML = pad( parseInt( totalSeconds / 60 ) );
         hoursLabel.innerHTML = pad( parseInt( totalSeconds / 3600 ) )
     }
     function pad( val ) {
         var valString = val + "";
         if( valString.length < 2 ) {
            return "0" + valString;
         } else {
            return valString;
         }
     }
   }

 })();

但是这些按钮在 atm 上不起作用。我不确定这是否也是实现目标的最佳解决方案,因此欢迎提出建议。

最佳答案

(function() {
  "use strict";
  var secondsLabel = document.getElementById('seconds'), minutesLabel = document.getElementById('minutes'), hoursLabel = document
      .getElementById('hours'), totalSeconds = 0, startButton = document.getElementById('start'), stopButton = document.getElementById('stop'), resetButton = document
      .getElementById('reset'), timer = null;

  startButton.onclick = function() {
    if (!timer) {
      timer = setInterval(setTime, 1000);
    }
  };

  stopButton.onclick = function() {
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
  };

  resetButton.onclick = function() {
    if (timer) {
      totalSeconds = 0;
      stop();
    }
  };

  function setTime() {
    totalSeconds++;
    secondsLabel.innerHTML = pad(totalSeconds % 60);
    minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
    hoursLabel.innerHTML = pad(parseInt(totalSeconds / 3600))
  }

  function pad(val) {
    var valString = val + "";
    if (valString.length < 2) {
      return "0" + valString;
    } else {
      return valString;
    }
  }

})();

关于javascript - 为计时器添加开始、停止和重置按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18121766/

相关文章:

javascript - 如何在 Fancybox 的 onComplete 事件中使用 $(this) ?

javascript - 如何在单击时隐藏和显示面板?

javascript - html 折叠/伸展树(Splay Tree)

javascript - OnClick 中函数的 jQuery 引用问题

javascript - Google Maps API v2 - 信息窗口底部的巨大差距

javascript - 用于至少一个字母表 (A-z) 的名称验证的正则表达式

javascript - Ajax 调用 Python 脚本。我缺少什么?

Javascript:_.sortBy 和 arr.sort 有什么区别?

javascript - 切换 Canvas 上下文

javascript - 如何在 .babelrc 文件上设置和保留语言语法类型