2014-03-28 59 views
0

我試圖在測試中循環10次(等待條件成立),但不知何故它不起作用。爲什麼我的同步代碼使用setTimeout在JavaScript中表現爲異步?

以下是我有:

// 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; 
    }; 

我的問題是,雖然我打電話倒計時結束之前我的狀態相當於true,從倒計時答案是undefined。所以,我的日誌進來是這樣的:

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

問題
從顯示的代碼,是有一個原因,爲什麼我的undefined登錄之前countDown通過並返回true

謝謝!

回答

6

呃,因爲setTimeout總是異步嗎?這是關鍵的一點。

這裏有一個可能對您:

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); 
} 

,直到條件滿足這將輪詢每秒一次,然後做相應的then回調給出。

+0

hm。好點:-)因此,任何想法如何使這項工作? – frequent

+0

我不明白你想做什麼,所以...不,對不起! –

+0

@常見有助於舉一個實例! – Kvothe

相關問題