3

在所有代码运行之前完成一个功能的噩梦。我正在尝试构建一个计数器,并且仅在代码完成时返回。

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

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

就像我说的,一个非常简化的例子——如果有人能指出错误,它会为我省去很多麻烦!

4

3 回答 3

4

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

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

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

// 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');
       }
    }
}
于 2012-05-24T15:09:48.793 回答
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()

于 2012-05-24T15:14:51.657 回答
-3

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

alert(timerCheck);
于 2012-05-24T15:04:57.647 回答