javascript for loop with a pause
I have a for loop that runs through an array of functions and invokes each one. ideally I would like to invoke them in a particular sequence since the output of one might effect the output of the others after it. is there anyway to do that without setting time intervals or timers?
Sorry...I guess i should have explained a bit more.. the example i have in mind might sometimes use ajax which means I would have to wait for ajax success before i carry on. ( other times I dont need to wait for ajax success) so i would like to set a condition such as if (success) { continue the for loop } in which success is a variable set 开发者_开发技巧on the success of each part of the loop.
Javascript runs synchronously, meaning that no two functions can be executing at the same time. So long as you run them in the correct order, you shouldn't have any problems.
When waiting for an ajax response you could either set the XMLHttpRequest to run synchronously (so, sjax rather than ajax) or set up some sort of function iterator that works like the following:
var FunctionIterator = {
nextFunction: 0,
functionArray: [],
callNext: function ()
{
this.functionArray[this.nextFunction].apply(null, arguments);
this.nextFunction++;
}
}
Then you use it like:
FunctionIterator.functionArray.push(someFunctionName);
FunctionIterator.functionArray.push(function (arg1) { alert(arg1); });
and
FunctionIterator.callNext(arg1, arg2, arg3);
Maybe self-explanatory but each time you run the callNext function, the next function is called and the array index is increased by 1 in preparation for the next function call.
If the functions run async you could also set them up to be called recursively (code totally untested, just to get the idea):
var funcarr = [];
function iterfuncs(arr){
arr.pop()();
if(arr.length >=1){
iterfuncs(arr);
}
}
if you have a lot of functions in your array and worry about your call-stack you can change the recursive call to be called with a timeout of 0 which lets the calling function return before the next one is executed. poor mans tail-recursion.
window.setTimeout(function(){ iterfuncs(arr); },0);
精彩评论