Search code examples
jquerysettimeoutsetintervalclearintervalcleartimeout

Start interval through timeout


I have this piece of code that initially starts an interval. Then with the push of a button, I want that interval to be stopped/cleared, wait X seconds, and then start the interval again.

This code starts the interval and works fine:

var timeout = undefined;
var interval = setInterval(bgScroll, timeBetweenSwap);

Then I want the interval to be stopped when i click the button, let it wait X seconds and start again (ofcourse pressing the button again should reset that amount of seconds)

$(document).on('click', '.bgscroller a', function(){
    clearInterval(interval);
    clearTimeout(timeout);

    var timeout = setTimeout(function(){
        var interval = setInterval(bgScroll, timeBetweenSwap);
    }, delayAfterClick);
});

Now when i click the button a few times the interval goes crazy and stacks up. I would suggest it to be cleared... any advice oh how I should fix this?

Kind regards, Narayan


Solution

  • In short, remove the last two var statements. Make it timeout = and interval = instead of var timeout = and var interval =.

    Your code is really close—it looks like you're shadowing the timeout and interval variables on the last few lines.

    This is the bit that's wrong:

    var timeout = setTimeout(function(){
        var interval = setInterval(bgScroll, timeBetweenSwap);
    }, delayAfterClick);
    

    It should look like this (very similar):

    timeout = setTimeout(function(){
        interval = setInterval(bgScroll, timeBetweenSwap);
    }, delayAfterClick);
    

    Note that we removed the var statements. This uses the same timeout and interval variables like above, rather than making new variables that happen to have the same names.