how do I pause and resume a timer?

前端 未结 4 1232
小鲜肉
小鲜肉 2020-12-29 00:58

I got this function that starts a timer on this format 00:00:00 whenever I click on a button. But I don\'t know how to do functions resume and pause. I\'ve found some snippe

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-29 01:19

    I think it will be better if you will create clock object. See code (see Demo: http://jsfiddle.net/f9X6J/):

    var Clock = {
      totalSeconds: 0,
    
      start: function () {
        var self = this;
    
        this.interval = setInterval(function () {
          self.totalSeconds += 1;
    
          $("#hour").text(Math.floor(self.totalSeconds / 3600));
          $("#min").text(Math.floor(self.totalSeconds / 60 % 60));
          $("#sec").text(parseInt(self.totalSeconds % 60));
        }, 1000);
      },
    
      pause: function () {
        clearInterval(this.interval);
        delete this.interval;
      },
    
      resume: function () {
        if (!this.interval) this.start();
      }
    };
    
    Clock.start();
    
    $('#pauseButton').click(function () { Clock.pause(); });
    $('#resumeButton').click(function () { Clock.resume(); });
    

提交回复
热议问题