在所有代码运行之前完成一项功能的噩梦。我试图建立一个计数器,并且只在代码完成时才返回。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";
}
}
就像我说的,更简单的例子 - 如果有人能指出这个错误,它会为我节省很多麻烦!
如果该函数调用并取决于异步函数,则无法同步获取函数的返回值。你必须使用回调。见http://stackoverflow.com/questions/2070275/javascript-closures-and-callbacks –
如果你有权访问jquery,你可以使用deferred和promise:http://stackoverflow.com/questions/5009194/how-to -use-jquery-deferred-with-custom-events – jbabey