[英]Why is my synchronous code using setTimeout behaving asynchronous in JavaScript?
I'm trying to loop 10x over a test (waiting for the condition to be true), but somehow it's not working. 我正在尝试在测试中循环10倍(等待条件变为真),但不知何故它不起作用。
Here is what I have: 这是我所拥有的:
// 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;
};
My problem is that although my condition equates to true
before I'm calling countdown, the answer from countDown is undefined
. 我的问题是,尽管在调用倒数计时之前我的条件等于true
,但countDown的答案是undefined
。 So my logs come in like this: 所以我的日志是这样的:
// true - before firing my countDown method
// undefined - should not log
// SENDING - response from countDown (= true)
Question : 问题 :
From the code displayed, is there a reason, why my undefined
is logged before countDown
is through and returns true
? 从显示的代码中,为什么有一个原因,为什么在countDown
通过之前返回undefined
并返回true
?
Thanks! 谢谢!
Erm, because setTimeout
is always asynchronous? 嗯,因为setTimeout
总是异步的? That's kind of the whole point. 这就是重点。
Here's a possibility for you: 这是您的一种可能:
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);
}
This will poll once every second until the condition is met, and then do whatever is given in the then
callback. 这将每秒轮询一次,直到满足条件为止,然后执行then
回调中提供的所有操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.