javascript - Trying to loop through images with a delay in canvas -


i have 25 images want show quickly, kinda slideshow without effects. images named 0 26.

i've tried setting loop , settimeout delay settimeout runs @ end of loop showing = 25 @ 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 show next.     alert('cp outside. = '+i);             } 

}

i followed solution how add delay in 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 working want to.

based on following snippet of code:

//clear image after 1 sec, loop show next. 

it appears have misunderstood how settimeout works. settimeout function not wait before returning. returns , schedules code/function passed execute @ later time (1 second in case). loop create 25 settimeouts simultaneously execute 1 second after loop executed.

there 2 solutions around this. one, create 25 settimeouts each 1 second later other:

for(var i=0; i<25; i++){     settimeout(function(){/* ... */}, 1000 * i); } 

alternatively call settimeout recursively process image list:

function foo (i) {     /* ... */     if (i >= 0) {         settimeout(foo(i-1),1000);    } }  foo(24); 

the second form more common.


in addition settimeout issue. need read on how closures work inside loops because in loop settimeouts execute value of i = 24 instead of i being values 1 24.

see: please explain use of javascript closures in loops


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -