Caballero
Caballero

Reputation: 12111

how to make functions with setTimeout() work in sequence?

Let's say I have 4 functions, every each of them has loops inside working with setTimeout(). How do I make those functions to run in sequence and not overlap? That is, how do I make each of them execute just after previous one is finished?

function1();
function2();
function3();
function4(); 

Upvotes: 1

Views: 1177

Answers (3)

kennebec
kennebec

Reputation: 104840

You can pass an array of functions,

and functions with arguments as arrays themselves.

Each must return before setting the timer for the next function

function fifo(what, delay){
    if(what.shift){
        var a, f= what.shift() || '';
        if(typeof f== 'function') f();
        else if(f.constructor== Array){
            a= f.splice(1, f.length);
            f[0].apply(this, a);
        }
        if(what.length){
            setTimeout(function(){
                fifo(what, delay);
            },
            delay);
        }

    }
};

function announce(){
    return alert(location.href)
}
var A= [[alert, 1], [alert, 2], announce, [alert, 'That\'s All!']];
fifo(A, 100);

Upvotes: 0

Raynos
Raynos

Reputation: 169531

function function1(cb) {
    if (someCondition) {
        setTimeout(function1, 0);
    } else {
        // we are done
        cb();
    }
}
...

function1(function() {
    function2(function() {
        function3(function() {
            function4();
        });
    });
});

The code does start getting messy if you go too deep so use some kind of flowcontrol like Step. Step might not work if it's not node though.

A simple queue might be :

var queue = {
    items: [],
    add: function() {
        for (var i = 0; i < arguments.length; i++) {
            this.items.push(arguments[i]);
        }
    },
    run: function() {
        var this = that;
        this.items.shift()(function() {
            that.run();
        })
    }
};

queue.add(function1, function2, function3, function4);

Here each function should take a function parameter done as its first argument and that should be called when the function is done.

Upvotes: 1

Matti Virkkunen
Matti Virkkunen

Reputation: 65166

Have each function call the next one after they're done.

If you want to make it "dynamic", implement a queue of functions and have each function call the next function in the queue when they're done. Then you can start a sequenced process by filling the queue and calling the first function.

Upvotes: 5

Related Questions