Question

I am trying to create a stopwatch on my site where I can count the time since the button was clicked. I then want to be able to stop the timer by clicking another button and store the elapsed time in a variable.

I am currently stuck at being able to stop the timer?

Everything I read seems to suggest that clearInterval will stop the timer but I am obviously not implementing it properly. Based on the below code (which is also available in this fiddle) where am I going wrong.

HTML

    <span id="start-counter">start counter</span>
    <span id="stop-counter">stop counter</span>
    <span id="counter"></span>

JS

    $("#start-counter").on("click", function(event){
    var pageVisisted = new Date();

    var test= setInterval(function() {
        var timeOnSite = new Date() - pageVisisted;
        var secondsTotal = timeOnSite / 1000;
        var minutes = Math.floor(secondsTotal / 60) % 3600;
        var seconds = Math.floor(secondsTotal)  % 60;

        document.getElementById('counter').innerHTML = minutes + ":" + seconds;
    }, 1000);
    });

    $("#stop-counter").on("click", function(event){
        //double check onclick is working
        //alert('test');
        clearInterval(test);
    });
Was it helpful?

Solution

Working Demo --> http://jsfiddle.net/pyRz9/

define test in outer scope

var test;
$("#start-counter").on("click", function (event) {
    var pageVisisted = new Date();

    test = setInterval(function () {
        var timeOnSite = new Date() - pageVisisted;
        var secondsTotal = timeOnSite / 1000;
        var minutes = Math.floor(secondsTotal / 60) % 3600;
        var seconds = Math.floor(secondsTotal) % 60;

        document.getElementById('counter').innerHTML = minutes + ":" + seconds;
    }, 1000);
});

$("#stop-counter").on("click", function (event) {
    //double check onclick is working
    //alert('test');
    clearInterval(test);
});

OTHER TIPS

Don’t do that

change:

var minutes = Math.floor(secondsTotal / 60) % 3600;

to:

var minutes = Math.floor(secondsTotal / 60) % 60;

Same working demo with condition and buttons: https://jsfiddle.net/shez1461/pyRz9/59/

var test;

if($('#start-counter').length == 1){
  $("#start-counter").on("click", function (event) {
      var pageVisisted = new Date();

      test = setInterval(function () {
          var timeOnSite = new Date() - pageVisisted;
          var secondsTotal = timeOnSite / 1000;
          var minutes = Math.floor(secondsTotal / 60) % 3600;
          var seconds = Math.floor(secondsTotal) % 60;

           document.getElementById('counter').innerHTML = minutes + ":" + seconds;
      }, 900);
  });
}

  $("#stop-counter").on("click", function (event) {
      //double check onclick is working
      //alert('test');
      clearInterval(test);
  });

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top