Javascript无法使用clearInterval停止计时器onclick

时间:2013-05-20 13:07:36

标签: javascript jquery setinterval clearinterval

我正在尝试在我的网站上创建一个秒表,我可以计算自点击按钮以来的时间。然后,我希望能够通过单击另一个按钮来停止计时器,并将经过的时间存储在变量中。

我目前只能停止计时器?

我读到的所有东西似乎都暗示clearInterval会停止计时器,但我显然没有正确实现它。基于以下代码(也可在this fiddle中找到)我在哪里出错。

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);
    });

3 个答案:

答案 0 :(得分:3)

工作演示--> http://jsfiddle.net/pyRz9/

在外部范围中定义test

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);
});

答案 1 :(得分:0)

不要那样做

变化:

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

为:

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

答案 2 :(得分:0)

与条件和按钮相同的工作演示: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);
  });