番茄钟:恢复按钮不起作用

时间:2015-09-07 13:35:08

标签: javascript jquery timer

我正在制作番茄钟。我使用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();
},
}

1 个答案:

答案 0 :(得分:0)

试试这个:

concept

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

}