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