Search code examples
jqueryfunctiontimeoutdelayintervals

Running functions in jQuery after delay


So, basically i have three functions and i want them to run one after another with two second delay.

I want to achieve something like:

firstFunction();
// Two seconds delay
secondFunction();
// Two seconds delay
thirdFunction();
// Two seconds delay
firstFunction();

And so on. I tried with setInterval, setTimeout, jquery delay, so far i achieved nothing - on best case scenario, all three functions run at the same time. To be exact, code of these three functions are fairly similar

var active = $(".active.two").removeClass('active');
if (active.next('img') && active.next('img').length) {
    active .next('img').addClass('active');
} else {
    active.siblings(":first-child").addClass('active');
}

I would appreciate if you could show me the right direction.


Solution

  • You can use setInterval to achieve this. You can make it simpler by storing the references to your functions in an array and then calling them in turn. Try this:

    function funcOne() {
        console.log('one');
    }
    
    function funcTwo() {
        console.log('two');
    }
    
    function funcThree() {
        console.log('three');
    }
    
    var i = 0;
    var funcs = [ funcOne, funcTwo, funcThree ];
    setInterval(function() {
        funcs[i % funcs.length]();
        i++;
    }, 2000);
    

    Example fiddle