2014-03-28 61 views
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

谢谢!

回答

6

呃,因为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回调给出。

+0

hm。好点:-)因此,任何想法如何使这项工作? – frequent

+0

我不明白你想做什么,所以...不,对不起! –

+0

@常见有助于举一个实例! – Kvothe

相关问题