我正在做番茄钟。我带了一个clock对象,添加了startpauseresume函数。为了在start函数中重复运行时钟,我添加了两个变量sb来保持会话和中断的原始时间。因此,在pause函数中,当我删除计时器时,会话和中断的原始时间将被删除。所以
resume功能时钟从头开始凝视。现在,如何以正确的方式编写pause函数以制作resume

这是JSfiddle链接。 http://jsfiddle.net/sajibBD/f18nh323/3/

提前致谢!

var Clock = {
sessionSeconds: 0,
breakSeconds: 0,

start: function () {
    var self = this;
    var s = this.sessionSeconds + 1;
    var b = this.breakSeconds + 1;

    this.interval = setInterval(function () {
        if (s > 0) {
            s -= 1;
            $('#state').text('Session');
            $("#min").text(Math.floor(s / 60 % 60));
            $("#sec").text(parseInt(s % 60));
        } else if (b > 0) {
            b -= 1;
            $('#state').text('Break');
            $("#min").text(Math.floor(b / 60 % 60));
            $("#sec").text(parseInt(b % 60));
        } else if (b === 0) {
            s = self.sessionSeconds + 1;
            b = self.breakSeconds + 1;
        }

        var min = $("#min").text();
        var sec = $("#sec").text();

        if (min.length === 1) {
            $("#min").text('0' + min);
        }
        if (sec.length === 1) {
            $("#sec").text('0' + sec);
        }

    }, 1000)
},

pause: function () {
    clearInterval(this.interval);
    delete this.interval;
},

resume: function () {
    if (!this.interval) this.start();
},
}

最佳答案

试试这个:

http://jsfiddle.net/f18nh323/5/

var Clock = {
sessionSeconds: 0,
breakSeconds: 0,

start: function () {
    var self = this;
    var s = this.sessionSeconds + 1;

    var b = this.breakSeconds + 1;

    this.interval = setInterval(function () {

        if (s > 0) {
            s -= 1;
            $('#state').text('Session');
            $("#min").text(Math.floor(s / 60 % 60));
            $("#sec").text(parseInt(s % 60));
        } else if (b > 0) {
            b -= 1;
            $('#state').text('Break');
            $("#min").text(Math.floor(b / 60 % 60));
            $("#sec").text(parseInt(b % 60));
        } else if (b === 0) {
            s = self.sessionSeconds + 1;
            b = self.breakSeconds + 1;
        }


        self.sessionSeconds = s;
        var min = $("#min").text();
        var sec = $("#sec").text();



        if (min.length === 1) {
            $("#min").text('0' + min);
        }
        if (sec.length === 1) {
            $("#sec").text('0' + sec);
        }


    }, 1000)
},

pause: function () {
    clearInterval(this.interval);
    delete this.interval;
},

resume: function () {
    if (!this.interval) this.start();
},


}

10-07 22:18