为什么使用setTimeout的同步代码在JavaScript中表现异步?

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

谢谢!

Nie*_*sol 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);
}
Run Code Online (Sandbox Code Playgroud)

这将每秒轮询一次,直到满足条件,然后执行then回调中给出的任何内容.

  • @frequent well`setTimeout()`立即返回.当计时器到期时,将调用您传递的函数.因此,如果您希望在经过一段时间后发生代码处理程序,则需要将代码放在*中. (2认同)