I have a for loop with a setTimeout function:
for (var i=0; i < variable; i++) {
setTimeout(function() {
screenArray.push(takeScreen());
sphere.rotateOnAxis(rotationVector, angle);
renderer.render(scene,camera);
}, 1);
}
The purpose there is to capture the canvas as a screenshot, rotate an object on the canvas, and repeat. Without the setTimeout function (even with a delay of 1), the canvas doesn't re-render fast enough before the canvas is capture and the screenshot looks weird.
The issue is that I would like do something with the array, screenArray, once everything is finished. But I can't seem to get anything to work. I'm just using console.log(screenArray) for testing for now, but the above simply logs [] to the console before it does the loop. Which I understand why (to a degree).
So I've been playing with callbacks, but every callback method I've tried either results in an error, [] multiple times, or screenArray being logged every interation of the loop (so it's not empty but it logs variable number of times). The following code does the latter (will output the array 4 times):
for (var i=0; i < screens; i++) {
setTimeout(function() { loopWork(callback) }, 1)
}
var callback = function(value) {
console.log(value);
}
function loopWork(callback) {
screenArray.push(takeScreen());
sphere.rotateOnAxis(rotationVector, angle);
renderer.render(scene,camera);
callback(screenArray);
}
I even tried combining that with combining the for loop with a separate callback function, but that just resulted in the same thing as the above (though I may have done that incorrectly).
What I want is for it to simply log screenArray when the for loop has completed (which also means waiting for the setTimeout), but I just can't get that working.
1as the duration of thesetTimeout? That's 1 millisecond, and all the timers start nearly exactly at the same time.1. I tried longer times, even up to10000, but that never changed anything. I'm not sure why1works (for the purpose to delaying the screenshot), but it does and I'm not going to question it right now.