1

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(); 

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1
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.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.