javascripthtmlstopwatch

Stopwatch in JavaScript


Before marking the question duplicate, I want to tell that I have been through all the stopwatch and JavaScript searches but as I am new to the JavaScript, so I can not come to the possible solution myself and I need the help from you guys.

What I want to achieve is to start and stop the watch with the same button. I can stop the watch but can not start again, can't figure out why.

Have a look at the following script and correct me.

var startTimer = setInterval(function(){myTimer()}, 1000);

function myTimer(){
  var current = new Date();
  document.getElementById("timer").innerHTML = current.toLocaleTimeString();
}

function start(st){
  // Problem is in this statement
  // How can I call the global function variable again that's startTimer
  window[st]();
  var elem = document.getElementById("myButton");
  elem.innerHTML = "Stop";
  elem.addEventListener("click", stop);
}

function stop(){
  clearInterval(startTimer);
  var elem = document.getElementById("myButton");
  elem.innerHTML = "Start";
  elem.addEventListener("click", start(startTimer));
}
<p id="timer"></p>
<button id="myButton" onclick="stop(startTimer)">Stop</button>


Solution

  • You want a single method to take care of the start/stop:

      var startTimer = setInterval(myTimer, 1000),
            timerElement = document.getElementById("timer"),
            buttonElement = document.getElementById("myButton");
        
        function myTimer(){
            var current = new Date();
            timerElement.innerHTML = current.toLocaleTimeString();
        }
        
        function toggle(){
            if (startTimer) {
                clearInterval(startTimer);
                startTimer = null;
                buttonElement.innerHTML = "Start";
            } else {
                buttonElement.innerHTML = "Stop";
                startTimer = setInterval(myTimer, 1000);
            }
        }
       <p id="timer"></p>
        <button id="myButton" onclick="toggle()">Stop</button>