如何暂停和恢复计时器?

esa*_*kwn 7 html javascript jquery setinterval pausing-execution

我有这个功能,只要我点击一个按钮,就会以00:00:00的格式启动计时器.但我不知道如何做功能恢复和暂停.我发现了一些我认为可能有用的片段,但我无法完成这些工作.我是新手在js中使用对象.

function clock() {
  var pauseObj = new Object();

  var totalSeconds = 0;
  var delay = setInterval(setTime, 1000);

  function setTime() {
    var ctr;
    $(".icon-play").each(function () {
      if ($(this).parent().hasClass('hide')) ctr = ($(this).attr('id')).split('_');
    });

    ++totalSeconds;
    $("#hour_" + ctr[1]).text(pad(Math.floor(totalSeconds / 3600)));
    $("#min_" + ctr[1]).text(pad(Math.floor((totalSeconds / 60) % 60)));
    $("#sec_" + ctr[1]).text(pad(parseInt(totalSeconds % 60)));
  }
}
Run Code Online (Sandbox Code Playgroud)

pad()只是添加前导零

Dan*_*sky 20

我认为如果你创建时钟对象会更好.查看代码(参见演示: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(); });
Run Code Online (Sandbox Code Playgroud)