Javascript 循环 - 等待值

Javascript loop - waiting on value

本文关键字:等待 循环 Javascript      更新时间:2023-09-26

一个在所有代码运行之前完成的函数做了一个噩梦。我试图在计数器中构建,并且仅在代码完成后返回。

我已经这样模仿了(我知道这并不好,但如果有人能指出我正确的路线,我将不胜感激):

//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";
    }
}

就像我说的,一个简化得多的例子 - 如果有人可以指出错误,这将为我节省很多麻烦!

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

您必须使用回调。有关更多详细信息,请参阅此问题。

例如,您的函数如下所示:

// 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');
       }
    }
}

正如 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()将在函数mySlowCode()完成后调用该函数letsDoIt()

您是否尝试过函数名称后没有括号?

alert(timerCheck);