Pasha Skender
Pasha Skender

Reputation: 417

JS stopping flow of control untill asynch setTimeout returns

I am attempting to use a synchronization counter and a recursive self invoking function to block flow of control to the remainder of my code until the set time out asynch function calls terminate and increment my synchronization counter. However it turns out that for some reason the setTimeout functions are never even called whether inside the recursive function or even outside of it. Does the recursive call somehow take priority over the setTimeout functions?

var localSynchCounter = 0;
(function asynchCall1(){
    //only runs the very first iteration of this function 
    console.log("running..: "+localSynchCounter);
    if (localSynchCounter == 0) {
        console.log("running autonymous first time");
        localSynchCounter ++;

        setTimeout(function() {
            localSynchCounter ++;
            console.log("set time out1 ocmpleted");
        }, 0);

        setTimeout(function() {
            localSynchCounter ++;
            console.log("set time out2 ocmpleted");
        }, 0);
    }

    else if (localSynchCounter == 3){
        console.log("functions have returned");
        return;
    }
    asynchCall1();

})(); 

Upvotes: 1

Views: 217

Answers (1)

Bergi
Bergi

Reputation: 664434

Does the recursive call somehow take priority over the setTimeout functions?

Yes, because it is synchronous (despite the name asynchCall1), while the timeouts are asynchonrous.

However it turns out that for some reason the setTimeout functions are never even called whether inside the recursive function or even outside of it.

They would (they have been "scheduled" for execution), if your script would have terminated. Currently your recursion is unbounded, because localSynchCounter is incremented once but never reaches 3 where the call would end.

To make it work, you will need to invoke asynchCall asynchronously (from the timeouts):

var localCounter = 0;
(function asyncCall(){
    //only runs the very first iteration of this function 
    console.log("running..: "+localCounter);
    if (localCounter == 0) {
        console.log("running autonomous first time");
        localCounter++;

        setTimeout(function() {
            localCounter++;
            console.log("settimeout 1 completed");
            asyncCall();
        }, 0);

        setTimeout(function() {
            localCounter ++;
            console.log("settimeout 2 completed");
            asyncCall();
        }, 0);
    } else if (localCounter == 3){
        console.log("functions have returned");
        return;
    }
})();

Upvotes: 2

Related Questions