2012-05-24 72 views
3

在所有代码运行之前完成一项功能的噩梦。我试图建立一个计数器,并且只在代码完成时才返回。Javascript循环 - 等待值

我模拟了这款像这样(我知道这不是美妙的,但如果有人能沿着正确的线路指向我,我会非常感激):

//I want this to alert "Done" 
alert(timerCheck()); 

function timerCheck() { 
    var finished; 
    var myLoop = 5; 
    for (i = 0; i < myLoop; i++) { 
        //This is emulating the slow code 
        window.setTimeout(checkFinished, 900); 
        alert(i); 
    } 
    function checkFinished() { 
        //I originally had the "return here, before realising my error 
        finished = true; 
    } 
    if (finished) { 
        //This is where my problem is  
        return "done"; 
    } 
} 

就像我说的,更简单的例子 - 如果有人能指出这个错误,它会为我节省很多麻烦!

+5

如果该函数调用并取决于异步函数,则无法同步获取函数的返回值。你必须使用回调。见http://stackoverflow.com/questions/2070275/javascript-closures-and-callbacks –

+0

如果你有权访问jquery,你可以使用deferred和promise:http://stackoverflow.com/questions/5009194/how-to -use-jquery-deferred-with-custom-events – jbabey

回答

4

如果函数调用并取决于异步函数,则无法同步获取函数的返回值。

你必须使用回调。有关更多详细信息,请参阅this question

例如,你的函数应该是这样的:

// pass a callback which gets the result of function 
timerCheck(function(result) { 
    alert(result); 
}); 

function timerCheck(callback) { 
    var myLoop = 5, 
     j = 0; 

    for (var i = 0; i < myLoop; i++) { 
     // This is emulating the slow code 
     // this will invoke `checkFinished` immediately, 
     // after 900ms, after 1800ms, after 2700ms and after 3600ms 
     window.setTimeout(checkFinished, i * 900); 
    } 

    function checkFinished() { 
     j++; 
     // after checkFinish was called 5 times, we invoke the callback 
     if(j === 5) { 
      callback('done'); 
     } 
    } 
} 
+0

当然!谢谢! – Richard

+0

你救了我的命:)) – Machete

-3

你有没有尝试过没有parens后函数名?

alert(timerCheck); 
+2

这只会提醒函数的正文,而不是调用函数。 –

0

由于FelixKling评论,你不能得到一个函数的返回值同步如果函数调用和依赖于异步函数。这些样的工作的一个解决办法是:

var finished = false; 

function mySlowCode() { 
    setTimeout(function() { 
     finished = true; 
    }, 1000); 
} 

function timerCheck() { 
    // legend... 
    (function waitForIt() { 
     setTimeout(function() { 
      if (!finished) { 
       waitForIt(); 
      } else { 
       // dary! 
       letsDoIt(); 
      } 
     }, 10); 
    })(); 
} 

function letsDoIt() { 
    alert("done"); 
} 

mySlowCode(); 
timerCheck(); 

功能timerCheck()会调用该函数letsDoIt()一旦功能mySlowCode()完成。