为计时器添加启动,停止,重置按钮

时间:2017-08-22 04:19:44

标签: javascript html button timer counter

我有这个计时计时器代码,想要添加启动,停止和重置按钮。它从页面加载开始。

<script type="text/javascript">
    var timerVar = setInterval(countTimer, 1000);
    var totalSeconds = 0;

    function countTimer() {
       ++totalSeconds;
       var hour = Math.floor(totalSeconds /3600);
       var minute = Math.floor((totalSeconds - hour*3600)/60);
       var seconds = totalSeconds - (hour*3600 + minute*60);

       document.getElementById("hour").innerHTML =hour;
       document.getElementById("minute").innerHTML =minute;
       document.getElementById("seconds").innerHTML =seconds;
    }
</script>

3 个答案:

答案 0 :(得分:3)

只需对hourminuteseconds进行一些简单操作,并使用clearIntervalsetInterval。在我的片段中,reset不会停止计时器,但通过几行代码很容易实现这一点。

&#13;
&#13;
window.onload = () => {
  let hour = 0;
  let minute = 0;
  let seconds = 0;
  let totalSeconds = 0;
  
  let intervalId = null;
  
  function startTimer() {
    ++totalSeconds;
    hour = Math.floor(totalSeconds /3600);
    minute = Math.floor((totalSeconds - hour*3600)/60);
    seconds = totalSeconds - (hour*3600 + minute*60);

    document.getElementById("hour").innerHTML =hour;
    document.getElementById("minute").innerHTML =minute;
    document.getElementById("seconds").innerHTML =seconds;
  }

  document.getElementById('start-btn').addEventListener('click', () => {
    intervalId = setInterval(startTimer, 1000);
  })
  
  document.getElementById('stop-btn').addEventListener('click', () => {
    if (intervalId)
      clearInterval(intervalId);
  });
  
   
  document.getElementById('reset-btn').addEventListener('click', () => {
     totalSeconds = 0;
     document.getElementById("hour").innerHTML = '0';
     document.getElementById("minute").innerHTML = '0';
     document.getElementById("seconds").innerHTML = '0';
  });
}
&#13;
<div>Hour: <span id="hour"></span></div>
<div>Minute: <span id="minute"></span></div>
<div>Second: <span id="seconds"></span></div>

<button id="start-btn">Start</button>
<button id="stop-btn">Stop</button>
<button id="reset-btn">Reset</button>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

//DOM CACHE
const startBtn = document.querySelector("#start-btn")
const stopBtn = document.querySelector("#stop-btn")
const resetBtn = document.querySelector("#reset-btn")
var minDigits = document.getElementById("min");
var secDigits = document.getElementById("sec");

//INITIALIZING VARIABLES
var hrs = 0;
var mins = 0;
var secs = 0;
var countSec = 0;
var timerVar = null;

//FUNCTIONS=============
function startCounter() {
    ++countSec;

    hrs = Math.floor(countSec /3600);
    mins = Math.floor((countSec - hrs*3600)/60);
    secs = countSec - (hrs*3600 + mins*60);

    if (secs < 10) {
        secDigits.innerHTML = "0" + secs;
    }  else { secDigits.innerHTML = secs; }

    minDigits.innerHTML = "0" + mins;   
}

startBtn.addEventListener('click', () => {
    timerVar = setInterval(startCounter, 1000);
})

stopBtn.addEventListener('click', () => {
    if (timerVar)
    clearInterval(timerVar);
});

resetBtn.addEventListener('click', () => {
    countSec = 0;
    secDigits.innerHTML = "00";
    minDigits.innerHTML = "00";
    clearInterval(timerVar);
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Clock JS</title>
</head>
<body>
    <div class="container">
        <header>
            <h1>SIMPLE COUNTER</h1>
            <p>At A Time No Time To Check Time</p>
        </header>

        <div class="clock-face">
            <div class="digital-time"></div>
            <div class="greeting"></div>
            
            <div class="screen">
                <h1 class="digits">
                    <span id="min" class="minutes">00</span>:<span id="sec" class="seconds">00</span>
                </h1>
            </div>
            
            <div class="clock-dial">
                <button id="start-btn">start</button>
                <button id="stop-btn">stop</button>
                <button id="reset-btn">reset</button>
            </div>
        </div>
    </div>
    

    <script src="app.js" charset="utf-8"></script>
</body>
</html>

答案 2 :(得分:0)

重复Adding start, stop, and reset buttons for a timer

但是因为没有HTML部分,所以有完整的答案(html + js感谢@closure)

(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;
    }
  }

})();
<p id='seconds'></p>
<p id='minutes'></p>
<p id='hours'></p>

<button id='start'>start</button>
<button id='stop'>stop</button>
<button id='reset'>reset</button>