I have 25 images I want to show really quickly, kinda like a slideshow without effects. My images are named 0 to 26.
I've tried setting a for loop and a setTimeout for the delay but the setTimeout runs only at the end of the for loop showing i = 25 at my Checkpoint.
JS:
function startAnimation(){
for(var i=0; i<25; i++){
setTimeout(function(){
img = new Image();
img.src = 'images/canvas/'+[i]+'.jpg';
img.onload = function(){ctx.drawImage(img,0,0, 850,194)}
alert('CP. In setTimeout. i= '+i);
},1000);
ctx.clearRect(0,0,canvas.width, canvas.height); //clear image after 1 sec, loop to show next.
alert('CP outside. i = '+i);
}
}
I followed this solution How do I add a delay in a JavaScript loop?:
function startAnimation(){
setTimeout(function(){
img = new Image();
img.src = 'images/canvas/'+[counter]+'.jpg';
img.onload = function(){ctx.drawImage(img,0,0, canvas.width,canvas.height)};
counter++;
if(counter<26){
startAnimation();
}
},150)
}
It seems to be working like I want it to.