add*_*itt 5 javascript for-loop continue
我需要暂停一个for循环而不是继续,直到我指定.对于我正在循环的数组中的每个项目,我运行一些在单独的设备上运行操作的代码,我需要等到该操作完成后再循环到数组中的下一个项目.
幸运的是,该代码/操作是一个游标并具有一个after:部分.
但是,它一直在运行整个for循环,我需要阻止它.有没有办法阻止循环继续,直到指定?或者可能是一种不同类型的循环或我应该使用的东西?
我的第一个(差)想法是在for循环中连续运行一个while循环,直到after:光标部分设置boolean为true.这只是锁定浏览器:(因为我担心它会.
我能做什么?我对javascript很新.我一直很喜欢我现在的项目.
这是while-loop尝试.我知道它的运行整个循环立即因为dataCounter从进入1到3(目前数组中的两个项目)瞬间:
if(years.length>0){
var dataCounter = 1;
var continueLoop;
for(var i=0;i<years.length;i++){
continueLoop = false;
baja.Ord.make(historyName+"?period=timeRange;start="+years[i][1].encodeToString()+";end="+years[i][2].encodeToString()+"|bql:select timestamp, sum|bql:historyFunc:HistoryRollup.rollup(history:RollupInterval 'hourly')").get(
{
ok: function (result) {
// Iterate through all of the Columns
baja.iterate(result.getColumns(), function (c) {
baja.outln("Column display name: " + c.getDisplayName());
});
},
cursor: {
before: function () {
baja.outln("Called just before iterating through the Cursor");
counter=0;
data[dataCounter] = [];
baja.outln("just made data["+dataCounter+"]");
},
after: function () {
baja.outln("Called just after iterating through the Cursor");
continueLoop = true;
},
each: function () {
if(counter>=data[0].length) {
var dateA = data[dataCounter][counter-1][0];
dateA += 3600000;
}
else {
var dateA = data[0][counter][0];
}
var value=this.get("sum").encodeToString();
var valueNumber=Number(value);
data[dataCounter][counter] = [dateA,valueNumber];
counter++;
},
limit: 744, // Specify optional limit on the number of records (defaults to 10)2147483647
offset: 0 // Specify optional record offset (defaults to 0)
}
})
while(continueLoop = false){
var test = 1;
baja.outln("halp");
}
dataCounter++;
}
}
Run Code Online (Sandbox Code Playgroud)
不要使用for循环来循环每个元素.你需要after:记住你刚刚完成的数组中的哪个元素然后转移到下一个元素.
像这样的东西:
var myArray = [1, 2, 3, 4]
function handleElem(index) {
module.sendCommand({
..., // whatever the options are for your module
after: function() {
if(index+1 == myArray.length) {
return false; // no more elem in the array
} else {
handleElem(index+1)} // the after section
}
});
}
handleElem(0);
Run Code Online (Sandbox Code Playgroud)
我假设你用一些选项调用一个函数(就像你想的那样$.ajax()),并且该after()部分是一个在你的进程结束时调用的函数(比如success()for $.ajax())
如果您调用的"模块"未在after()回调中正确结束,则可以使用setTimeout()以延迟启动下一个元素上的进程
编辑:使用您的真实代码,它将是这样的:
function handleElem(index) {
baja.Ord.make("...start="+years[index][1].encodeToString()+ "...").get(
{
ok: ...
after: function() {
if(index+1 == years.length) {
return false; // no more elem in the array
} else {
handleElem(index+1)} // the after section
}
}
});
}
Run Code Online (Sandbox Code Playgroud)