user2981607
user2981607

Reputation: 27

Restart SetInterval in Javascript

I'm having a hard time restarting the time to 10 seconds after i clear the interval. when the status is success it should re run again the set Interval

Below is my code :

<code>
var countdown = 10;
var startTime = currTimer();
var myInterval = setInterval(function() {
countdown--;
if(countdown == 0){
    var endTime = currTimer();
    clearInterval(myInterval);
    countdown = 10;

    if (status == "success"){
        setTimeout(function(){myInterval}, 200); 
    }

}

io.sockets.emit('timer', { countdown: countdown });
}, 2000);
</code>

Upvotes: 1

Views: 1385

Answers (1)

MildlySerious
MildlySerious

Reputation: 9170

The best way would propably be to save the function in a variable that you can pass to the setInterval call. This way it becomes a single, easiliy repeatable line.

var countdown = 10;
var startTime = currTimer();
var onInterval = function() {
    countdown--;
    if(countdown == 0){
        var endTime = currTimer();
        clearInterval(myInterval);
        countdown = 10;

        if (status == "success"){
            setTimeout(function(){
                myInterval = setInterval(onInterval, 2000);
            }, 200); 
        }

    }

    io.sockets.emit('timer', { countdown: countdown });
};
var myInterval = setInterval(onInterval, 2000);

Upvotes: 1

Related Questions