vendredi 27 avril 2018

Javascript Timers: multiple timers not stopping

I am trying to establish multiple timers that all increment from 0 until their corresponding button is stopped. Currently the second timer begins 1 second ahead of the first timer, and neither stop button works. Note: Its hard-coded to start at 0 for both functions.

    <!DOCTYPE html>
    <html>
    <body>
      <div id="timer1"></div>
      <button onclick="myStopFunction()">Stop the alert</button>
      <div id="timer2"></div>
      <button onclick="myStopFunction()">Stop the alert</button>
    <script>
    var timerVar = setInterval(countTimerQueue1, 1000);
    var totalSeconds = 0;
    function countTimerQueue1() {
       ++totalSeconds;
       var seconds =  pad(totalSeconds % 60);
       var minute = pad(parseInt(totalSeconds / 60));

       document.getElementById("timer1").innerHTML =  minute + ":" + seconds;
     }
     var timerVar = setInterval(countTimerQueue2, 1000);
     var totalSeconds = 0;
     function countTimerQueue2() {
        ++totalSeconds;
        var seconds =  pad(totalSeconds % 60);
        var minute = pad(parseInt(totalSeconds / 60));

        document.getElementById("timer2").innerHTML =  minute + ":" + seconds;
      }
     function pad(val) {
      var valString = val + "";
      if (valString.length < 2) {
        return "0" + valString;
      } else {
        return valString;
      }
    }
    function myStopFunction() {
        clearInterval(timeVar);
    }
    </script>
    </body>
    </html>




Aucun commentaire:

Enregistrer un commentaire