Javascript 循环 - 等待值
Javascript loop - waiting on value
一个在所有代码运行之前完成的函数做了一个噩梦。我试图在计数器中构建,并且仅在代码完成后返回。
我已经这样模仿了(我知道这并不好,但如果有人能指出我正确的路线,我将不胜感激):
//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);
相关文章:
- Javascript在for循环中等待处理请求
- JavaScript循环并等待函数
- 在等待异步任务时永久循环
- 等待循环调用的所有承诺完成
- 如何让foreach循环等待$http.get完成后再继续
- 如何使for循环等待回调返回值
- 在 JS 中使 for 循环在没有库的情况下等待
- Nodejs async.each 等待第一个循环
- 如何在数组中循环,等待每个项目之间的时间
- 如何在for循环中等待一个,直到ajax调用完成
- NodeJS - Bluebird:等待循环完成
- 等待循环中的函数完成
- 等待循环完成
- 使异步/等待循环按顺序执行
- 在输出数据之前,等待循环完成每个数组项的 $.getJSON
- Jquery等待循环中带有ajax调用的函数完成-单击按钮后刷新
- 等待循环结束并执行第二个函数
- 如何等待'等待'循环返回
- 如何在退出循环之前等待循环内的异步进程完成
- Javascript:等待循环中的函数在下一次迭代之前完成执行