我试图弄清楚如何让'暂停'和'停止'按钮在我的计时器上工作

时间:2017-12-15 17:07:28

标签: javascript jquery timer

我想弄清楚如何让我的计时器正常工作。计时器本身有效,但“暂停”和“停止”按钮似乎没有响应。

这是我到目前为止的代码:

    var h1 = document.getElementsByTagName('h1')[0],
      start = document.getElementById('start'),
      pause = document.getElementById('pause'),
      stop = document.getElementById('stop'),
      seconds = 0,
      minutes = 0,
      hours = 0,
      t;

    function add() {
      seconds++;
      if (seconds >= 60) {
        seconds = 0;
        minutes++;
        if (minutes >= 60) {
          minutes = 0;
          hours++;
        }
      }

      h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") +
        ":" + (seconds > 9 ? seconds : "0" + seconds);

      timer();
    }

    function timer() {
      t = setTimeout(add, 1000);
    }
    timer();        

//START BUTTON
    $("#start").on("click", function() {
      clearTimeout(t);
      timer();
    });

无法获得对此的回复:

//PAUSE BUTTON
    $("#pause").on("click", function() {
      clearTimeout(t);
    });
//STOP BUTTON
    $("#stop").on("click", function() {
      h1.textContent = "00:00:00";
      seconds = 0;
      minutes = 0;
      hours = 0;
    });

1 个答案:

答案 0 :(得分:0)

这个小提琴有效: https://jsfiddle.net/0a41am3v/

var h1 = document.getElementsByTagName('h1')[0];
var start = document.getElementById('start');
var pause = document.getElementById('pause');
var stop = document.getElementById('stop');
var seconds = 0;
var minutes = 0;
var hours = 0;
var t;

function add()
{
    seconds++;
    if (seconds >= 60)
    {
        seconds = 0;
        minutes++;
        if (minutes >= 60) 
        {
            minutes = 0;
            hours++;
        }
    }

    h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") +
        ":" + (seconds > 9 ? seconds : "0" + seconds);

    timer();
}

function timer()
{
      t = setTimeout(add, 1000);
}


$("#start").on("click", function() {
        $("#start").empty().append("start");
        clearTimeout(t);
        timer();
    });

$("#pause").on("click", function(){
    clearTimeout(t);
    $("#start").empty().append("resume");
});

$("#stop").on("click", function() {
    $("#start").empty().append("start");
    clearInterval(t);
    h1.textContent = "00:00:00";
    seconds = 0;
    minutes = 0;
    hours = 0;
 });