JavaScript Stopwatch

Before marking a duplicate question, I want to say that I went through all the stopwatch and JavaScript sessions, but since I'm new to JavaScript, so I can’t come to the most possible solution, and I need help from you guys.

What I want to achieve is to start and stop the clock using the same button. I can stop the clock, but I can not start again, I can not understand why.

Take 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 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>
Run codeHide result
+4
source share
2 answers

You want one method to take care of start / stop:

<p id="timer"></p>
<button id="myButton" onclick="toggle()">Stop</button>

<script type="text/javascript">
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);
    }
}
</script>
+3
source

Why clear your interval? catching up, where is the remaining interval.

var timer  = document.getElementById("timer"),
    paused = 0;

setInterval(function(){
  if(!paused) timer.innerHTML =  new Date().toLocaleTimeString();
}, 1000);

document.getElementById("myButton").addEventListener("click", function(){
  this.innerHTML = (paused ^= 1) ? "Start" : "Stop";
});
<p id="timer"></p>
<button id="myButton">Stop</button>
Run codeHide result

P.S: , , fn.

(paused ^= 1) 1,0,1,0,1..., boolean.

+1

All Articles