fre*_*ent 0 javascript jquery timeout qunit jquery-mobile
我试图在测试中循环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;
};
Run Code Online (Sandbox Code Playgroud)
我的问题是虽然我的条件相当于true我打电话倒计时之前,但是来自countDown的答案是undefined.所以我的日志是这样的:
// true - before firing my countDown method
// undefined - should not log
// SENDING - response from countDown (= true)
Run Code Online (Sandbox Code Playgroud)
问题:
从显示的代码中,是否有一个原因,为什么我undefined的记录countDown是通过并返回true?
谢谢!
呃,因为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);
}
Run Code Online (Sandbox Code Playgroud)
这将每秒轮询一次,直到满足条件,然后执行then回调中给出的任何内容.