Javascript loop - wait by value

Having a nightmare with a function that ends before running all the code. I try to build a counter and return only after the code completes.

I imitated it this way (I know that this is not fantastic, but if someone could point me to the correct lines, I would be very grateful):

//I want this to alert "Done"
alert(timerCheck());

function timerCheck() {
    var finished;
    var myLoop = 5;
    for (i = 0; i < myLoop; i++) {
        //This is emulating the slow code
        window.setTimeout(checkFinished, 900);
        alert(i);
    }
    function checkFinished() {
        //I originally had the "return here, before realising my error
        finished = true;
    }
    if (finished) {
        //This is where my problem is 
        return "done";
    }
}

As I said, a very simplified example - if someone can point out an error, this will save me from the hassle!

+3
source share
3 answers

You cannot get the return value of a function synchronously if this function calls and depends on asynchronous functions.

You need to work with callbacks. See this question for more details .

For example, your function would look like this:

// pass a callback which gets the result of function
timerCheck(function(result) {
    alert(result);
});

function timerCheck(callback) {
    var myLoop = 5,
        j = 0;

    for (var i = 0; i < myLoop; i++) {
        // This is emulating the slow code
        // this will invoke `checkFinished` immediately, 
        // after 900ms, after 1800ms, after 2700ms and after 3600ms
        window.setTimeout(checkFinished, i * 900);
    }

    function checkFinished() {
       j++;
       // after checkFinish was called 5 times, we invoke the callback
       if(j === 5) {
           callback('done');
       }
    }
}
+4

FelixKling, , . :

var finished = false;

function mySlowCode() {
    setTimeout(function() {
        finished = true;
    }, 1000);
}

function timerCheck() {
    // legend...
    (function waitForIt() {
        setTimeout(function() {
            if (!finished) {
                waitForIt();
            } else {
                // dary!
                letsDoIt();
            }
        }, 10);
    })();
}

function letsDoIt() {
    alert("done");
}

mySlowCode();
timerCheck();

timerCheck() letsDoIt() mySlowCode().

0

Have you tried this without pairs after the function name?

alert(timerCheck);
-3
source

All Articles