3

I have this count-up timer code and want to add start, stop and reset button. It start right at the page load.

<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>
2

3 Answers 3

5

It's just some simple manipulation of hour, minute and seconds and making use of clearInterval and setInterval. In my snipper, reset won't stop the timer, but it's easy to make that happen by a few lines of code.

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';
  });
}
<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>

2
  • @KryptoNeko9 I'm glad I could help, and I'd very appreciate it if you can accept my answer too.
    – kevguy
    Aug 22, 2017 at 8:46
  • The example works perfectly, and it's so easy to understand! Thank you.
    – Zack Zilic
    Sep 11, 2018 at 13:46
1

Duplicate of Adding start, stop, and reset buttons for a timer

but just because there is not the HTML part, there is the full answer (html + js thanks to @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>

1
  • Maybe you want to flag the question as possible duplicate?
    – maazadeeb
    Aug 22, 2017 at 5:24
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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.