SetTimeout inside a for loop, getting the final value (waiting for the loop to finish)
I have a for loop with a function setTimeout
:
for (var i=0; i < variable; i++) {
setTimeout(function() {
screenArray.push(takeScreen());
sphere.rotateOnAxis(rotationVector, angle);
renderer.render(scene,camera);
}, 1);
}
The goal is to freeze canvas
as a screenshot, rotate the object on the canvas and repeat. Without the function setTimeout
(even with a delay of 1) the canvas won't re-render fast enough before the canvas is captured and the screenshot looks weird.
The problem is, I would like to do something with the array screenArray
as soon as everything is complete. But I can't get anything to work. I'm just using it console.log(screenArray)
for testing at the moment, but the above just logs []
to the console before it does the loop. Which I understand why (to some extent).
So, I've been playing around with callbacks, but every callback method I've tried either results in an error, []
multiple times, or screenArray
every interval of the loop is logged (so it's not empty, but it logs a 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 to combine this with combining the for loop with a separate callback function, but this resulted in the same as above (although I may have done it wrong).
I want it to just log screenArray
when the for loop has finished (which also means waiting setTimeout
), but I just can't get that to work.
source to share
you need to print the array when all the timings are finished. Try it:
var j=0;
for (var i=0; i < variable; i++) {
setTimeout(function() {
screenArray.push(takeScreen());
sphere.rotateOnAxis(rotationVector, angle);
renderer.render(scene,camera);
j++;
if (j == variable) console.log(screenArray);
}, 1);
}
source to share
----------
var screenCapture = (function(){
var screenArray = [];
return{
loopScreen : function(length){
var count = 0;
var _this = this;
var intvl = setInterval(function () {
if(count < length){
_this.captureScreen(count);
count++;
}else{
clearInterval(intvl);
console.log(screenArray);
}
}, 1)
},
captureScreen : function(val){
screenArray.push(val)
}
}
})()
screenCapture.loopScreen(10);
source to share