我知道这种问题已经被一遍又一遍地问过(我已经在Stackoverflow和其他地方阅读并重读了许多内容)。
我尝试使用闭包,匿名函数和其他方法,但是我什么也没得到,因为我不是专家代码):。
话虽如此,这是我的问题:
function A (a) {
for (var i in a) {
var x = a[i];
function B (x); // wait for the end of the function B before next loop
}
}
....
function B (x) {
//do things with "x" and repeat the function B until a condition is true and then return to the function A
}
我尝试了很多事情(可能还不够),但没有一个能正常工作...
所以在此先感谢您的建议
问候
编辑:
好在这里完整的代码:
var Test = {
......
setProgress: function(count) {
var win = Test.getMainWindow();
var progressMeter = win.document.getElementById("progressMeter");
progressMeter.value = count;
},
cancelCheck: function(event) {
var win = Test.getMainWindow();
win.document.getElementById("cancel").value = "cancel";
},
timeout: function (item) {
var win = Test.getMainWindow();
win.document.getElementById("progressMeterText").value = item;
var stat = Test.getStatus()
if (stat !== "loading" || win.document.getElementById("cancel").value == "cancel") {
// if cancel button is clicked
if (win.document.getElementById("cancel").value == "cancel") {
Test.setProgress(100);
Test.stop();
win.document.getElementById("cancel").value = "";
win.document.getElementById("progressMeter").collapsed=true;
win.document.getElementById("cancel").hidden=true;
win.document.getElementById("progressMeterText").hidden=true;
}
// end of the loading
else if (stat !== "loading") {
Test.setProgress(100);
win.document.getElementById("progressMeter").collapsed=true;
win.document.getElementById("cancel").hidden=true;
win.document.getElementById("progressMeterText").hidden=true;
win.document.getElementById("cancel").value = "";
}
// loading is running
else {
count = count+5;
if (count == 100) {
count = 0;
}
Test.setProgress(count);
setTimeout (Test.timeout, 100 , item);
}
}
},
getStuff: function (items) {
for(var i in items) {
var item = items[i];
if (!item.host || (items && item.id != items)) continue;
var listener = new Test.GetListener(item);
listener.instance = new TestGet(item, listener).execute();
count = 10;
Test.setProgress(count);
var buttoncancel = win.document.getElementById("cancel");
buttoncancel.addEventListener ('click', Test.cancelCheck, false);
Test.timeout(item);
.....
}
.....
}
}
最佳答案
看来B
是一个递归函数,但是您仍然应该仅通过B();
调用它。
function A(a) {
for (var i in a) {
B(a[i]);
}
}
function B(x) {
var ret = dosomething(x);
if (condition(ret)) {
return;
}
return B(ret);
}