Proper way to wait for one function to finish before continuing?

I have two JS functions. One calls the other. Within the calling function, I’d like to call the other, wait for that function to finish, then continue on. So, for example/pseudo code:

function firstFunction(){
    for(i=0;i<x;i++){
        // do something
    }
};

function secondFunction(){
    firstFunction()
    // now wait for firstFunction to finish...
    // do something else
};

I came up with this solution, but don’t know if this is a smart way to go about it.

var isPaused = false;

function firstFunction(){
    isPaused = true;
    for(i=0;i<x;i++){
        // do something
    }
    isPaused = false;
};

function secondFunction(){
    firstFunction()
    function waitForIt(){
        if (isPaused) {
            setTimeout(function(){waitForIt()},100);
        } else {
            // go do that thing
        };
    }
};

Is that legit? Is there a more elegant way to handle it? Perhaps with jQuery?

11 Answers
11

Leave a Comment