This is a follow-up question to: How to suspend JavaScript to allow render
I wrote a function that does a kind of suspended for-loop (to allow rendering in between):
function loop(count, callback){
var counter = 0
var iteration = function(){
callback(counter)
counter ++;
if (counter < count){
setTimeout(iteration, 0)
}
}
iteration();
}
This works nicely, using e.g. loop(100, function(i){ console.log(i) } ). And allows the browser to render in between each iteration.
However, problems occur when executing stuff after the loop, since there is no guarantee that the loop has finished. Actually, I'm thinking there is a guarantee that it has not (since the main thread continues after setTimeout has been called the first time). This is exacerbated when nesting these kind of loops:
loop(10, function(i){
loop(10, function(j){
console.log(i + '-' + j)
})
})
/// This definitely does not output the numbers in order...
My use case is that I am running a number of simulations, each consisting of a number of steps, and I want to render in between each. Am I going about this the wrong way?
function loop(count,callback,callback_finish){if(counter<count){}else{callback_finish()}}.