trailblazer
trailblazer

Reputation: 1451

wait till function completes calling other functions

I have a function1 that calls another function2. Function2 has a for loop in which it calls function3. I want to execute a statement after all 3 calls to function 3 have finished executing. How do I achieve it?

function1: function(){
    function2(args, doSomething(returnValue) {
        if(returnValue == true){
            // do something here
        }
    });
}

function2: function(args, callback){
    for(var i = 0; i < 3; i++){
        function3(args);
    }

    // if function3 completed all 3 times
    callback(true);
}

Upvotes: 1

Views: 107

Answers (1)

dj0965
dj0965

Reputation: 135

I think all you need to do is to make a variable that increments each time the for loop runs in function2() and check if it is high enough outside of the for loop.

var timesCalled = 0
function1: function(){
    function2(args, doSomething(returnValue) {
        if(returnValue == true){
            // do something here
        }
});
}
function2: function(args, callback){
    for(var i = 0; i < 3; i++){
        function3(args);
        timesCalled++
    }

    if (timesCalled >= 2){// if function3 completed all 3 times
        callback(true);
    }
}

If you want to make sure that function3 does what you want it to 3 times then put the increment in function3. I hope this helps!

Upvotes: 1

Related Questions