You can use "asynchronous pseudo-recursion" instead of a for
loop, with the general pattern that I use being:
var pods = [ ... ];
(function loop() {
if (pods.length) {
var pod = pods.shift(); // take (and remove) first element
// do something with "pod"
...
// recurse - put this inside a finish callback if "do something" is async
loop();
}
})(); // closing braces start invocation immediately
where in your case, the call to loop
should be the last thing inside your callback function.
NB: This pattern can also be used to avoid the "browser not responding" error seen with longer running non-async operations by replacing the call to loop()
with setTimeout(loop, 0)
.
This use of setTimeout
turns a synchronous recursive function into an asynchronous pseudo-recursive one, in the process avoiding the possibility of any stack overflow errors.
The only downside is the 4ms minimum delay between iterations.