Я пытаюсь зациклить 10 раз над тестом (ожидая, что условие будет истинным), но почему-то это не работает.
Вот что я имею:
// 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
пока я не вызываю обратный отсчет, ответ из countDown не undefined
. Итак, мои журналы поступают так:
// true - before firing my countDown method
// undefined - should not log
// SENDING - response from countDown (= true)
Вопрос:
Из отображаемого кода есть причина, почему мой undefined
регистрируется до того, как countDown
прошел и возвращает true
?
Благодарю!
Erm, потому что 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
обратного вызова.