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
?
謝謝!
hm。好點:-)因此,任何想法如何使這項工作? – frequent
我不明白你想做什麼,所以...不,對不起! –
@常見有助於舉一個實例! – Kvothe