在所有代碼運行之前完成一項功能的噩夢。我試圖建立一個計數器,並且只在代碼完成時才返回。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