gpt4 book ai didi

Javascript 循环 - 等待值

转载 作者:行者123 更新时间:2023-11-29 15:46:16 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

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

您必须使用回调。参见 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');
}
}
}

关于Javascript 循环 - 等待值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10740042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com