Question

I am attempting to temporarily pause a setInterval when the "next" button is clicked. Currently it stops the current setinterval but doesn't start it again after 10 seconds.

I have a simple image rotator that changes the image ever 4 seconds. When the "Next" button is clicked I want it to pause the interval for 10 seconds before starting the 4 second rotation again.

Heres the code so far (has been simplified):

var ic = $('#imageContainer');
var numItems = $('.image').size();
var position = 0;
ic.css('left', '0px');

var inter;

function rotate() {
    inter = setInterval(function () {
        if (position == (numItems - 1)) {
            console.log(position);
            $('.image').first().insertAfter($('.image').last());
            ic.css('left', '+=400px');
            position--;
        }
        ic.animate({
            left: "-=400px"
        });
        position += 1;
    }, 4000);
}
rotate();

$('#next').click(function () {
    clearInterval(inter);
    nextInter = setInterval(function () {
        rotate();
    }, 10000);
    clearInterval(nextInter);
});
Was it helpful?

Solution

This is happening because you are clearing the nextInter just one line after you've created it.

nextInter = setInterval(function(){rotate();}, 10000 );
clearInterval(nextInter);

However, if you remove the last clearInterval, your nextInter interval will call rotate every 10 seconds, that will set a new interval for every 4 seconds. This certainly will cause unexpected behavior. I think you are looking for setTimeout instead.

$('#next').click(function () {
    clearInterval(inter);
    setTimeout(rotate, 10000);
});

Also, if you want to prevent from doing multiple rotates if you click the next button multiple times, you could create a variable outside your callback scope to store your setTimeout instance and then clear it when the button is clicked. Example:

var rotateTimeout;
$('#next').click(function () {
    clearInterval(inter);
    clearTimeout(rotateTimeout);
    rotateTimeout = setTimeout(rotate, 10000);
});

OTHER TIPS

After scheduling the nextInter, you are clearing it soon after it is executed.

What you need here is setTimeout() instead of setInterval(). What you need was to call rotate after 10 seconds but setInterval will call it in every 10 seconds so you were clearing it but the problem was you were clearing it before it had a chance to execute rotate even once.

$('#next').click(function () {
    clearInterval(inter);
    setTimeout(rotate, 10000 );
});

You can do this using setTimeout:

$('#next').click(function () {
    clearInterval(inter);
    nextInter = setTimeout(rotate, 10000);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top