JohnRobertPett
JohnRobertPett

Reputation: 1183

Stop and start setInterval()

I am trying to stop a loop so other things can run, then return to the loop again at the correct time in the sequence. The code I have runs once, but then seems to be unable to run after I use clearInterval();

function runPlanner() {

    var plannerInterval = setInterval(function(){

        imageCounter++;

        var imageTotal = $('li img').length;

        if (imageCounter > imageTotal + 1) {
            $('li img').hide();
            imageCounter = 0;
            clearInterval(plannerInterval);
        } else {
            $('li img:nth-child(' + imageCounter +')').fadeIn('slow');
        }

        console.log('image counter:',imageCounter);
        console.log('image total:',imageTotal);
    }, 2500);

}

Then I can run this initially, with:

runPlanner();

But if the condition is met, where clearInterval is called, then using that function call doesn't work. Any ideas, please!?

Upvotes: 0

Views: 106

Answers (1)

Chokchai
Chokchai

Reputation: 1722

Try to use setTimeout style. so you will not have a problem with clearInterval anymore.

like this.

function runPlanner() {

        imageCounter++;

        var imageTotal = $('li img').length;

        if (imageCounter > imageTotal + 1) {
            $('li img').hide();
            imageCounter = 0;
        } else {
            $('li img:nth-child(' + imageCounter +')').fadeIn('slow');

            // re-called `runPlanner` after 2500 sec
            setTimeout(runPlanner, 2500);
        }

        console.log('image counter:',imageCounter);
        console.log('image total:',imageTotal);

}

runPlanner();

Upvotes: 1

Related Questions