1

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

我目前无法停止计时器?

我读到的所有内容似乎都表明 clearInterval 会停止计时器,但我显然没有正确实现它。基于以下代码(也可在此小提琴中获得中找到)我哪里出错了。

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

3 回答 3

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);
});
于 2013-05-20T13:08:49.647 回答
0

不要那样做

改变:

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

至:

var minutes = Math.floor(secondsTotal / 60) % 60;
于 2014-06-30T10:50:16.053 回答
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);
  });

于 2017-03-14T15:11:34.760 回答