简体   繁体   English

setInterval():如何停止然后重新启动?

[英]setInterval(): How to stop then start itself again?

In a if statement, I want the interval to clear itself and then call object function of itself again to restart the interval. 在if语句中,我要清除间隔,然后再次调用其自身的对象函数以重新启动间隔。

Is such thing possible? 这样的事情可能吗?

I tried it this way, but I'm getting unexpected behavior. 我以这种方式尝试过,但是出现了意外的行为。 I can see that the log keeps on logging every 200ms. 我可以看到日志每200ms持续记录一次。 While it should have stopped since the interval was stopped and restarted and the condition wouldn't evaluate to true anymore. 尽管自间隔停止并重新启动以来它应该已经停止,但该条件不再评估为true。

DateTime.prototype = {
    start: function () {
        var self = this;

        sendAjaxRequest(this.timeUrl, function () {
            var previousTime = new Date().getTime();

            this.tickIntervalId = setInterval(function tick() {
                var currentTime = new Date().getTime();

                if ((currentTime - previousTime) < 0) {
                    console.log('You changed your time backwards. Restarting.');

                    self.stop(); // <-- stopping itself
                    self.start(); // <-- call to same method its running from

                    return;
                }

                self.dateElement.innerHTML = new Date();

                previousTime = currentTime;

                return tick;
            }(), 200);
        });
    },

    stop: function () {
        clearInterval(this.tickIntervalId);

        this.tickIntervalId = null;
    }
}

I think the scope is wrong for the setInterval call. 我认为setInterval调用的范围是错误的。

Try to change 尝试改变

this.tickIntervalId = setInterval(function tick() {

to use self 使用自我

self.tickIntervalId = setInterval(function tick() {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM