Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 926
Imam Bux Avatar asked Jun 08 '15 05:06

Imam Bux


2 Answers

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>
like image 130
Konstantin Dinev Avatar answered Sep 19 '22 22:09

Konstantin Dinev


Why clearing your interval? catch-up where the interval left.

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>

P.S: Always cache elements you plan to reuse, specially if inside an interval fn.

(paused ^= 1) is used to toggle ones and zeroes 1,0,1,0,1... used than as boolean.

like image 22
Roko C. Buljan Avatar answered Sep 17 '22 22:09

Roko C. Buljan