简体   繁体   中英

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.

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. While it should have stopped since the interval was stopped and restarted and the condition wouldn't evaluate to true anymore.

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.

Try to change

this.tickIntervalId = setInterval(function tick() {

to use self

self.tickIntervalId = setInterval(function tick() {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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