Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

javascript - how do I pause and resume a timer?

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 snippets that I thought could be helpful but I couldn't make those work. I'm new to using objects in 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)));
  }
}

pad() just adds leading zeros

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...