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){
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
source
share