Domanda

I'm trying to loop 10x over a test (waiting for the condition to be true), but somehow it's not working.

Here is what I have:

// my counter
$.testHelper.countDown = function(test, iteration) {
    var ticker = iteration || 0;
    if (ticker > 10) {
      return false;
     }
    window.setTimeout(function() {
        if (test === true) {
            console.log("SENDING");
            return true;
        }
        ticker += 1;
        $.testHelper.countDown(test, ticker);
     }, 1000);
    };

    // my test     
    $.testHelper.testForElement = function(element) {
        var result;   
        console.log($i.find(element).length > 0); // true
        result = $.testHelper.countDown(
             $i.find(element).length > 0
        );
        console.log(result);  // undefined
        return result;
     };

My problem is that although my condition equates to true before I'm calling countdown, the answer from countDown is undefined. So my logs come in like this:

// true - before firing my countDown method
// undefined - should not log
// SENDING - response from countDown (= true)

Question:
From the code displayed, is there a reason, why my undefined is logged before countDown is through and returns true?

Thanks!

È stato utile?

Soluzione

Erm, because setTimeout is always asynchronous? That's kind of the whole point.

Here's a possibility for you:

function when(condition,then) {
    // condition must be a callback that returns `true` when the condition is met
    if( condition()) then();
    else setTimeout(function() {when(condition,then);},1000);
}

This will poll once every second until the condition is met, and then do whatever is given in the then callback.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top