I have an onload function within a for statement that is producing unexpected results.
The for loop loops through an array of images. I'm wanting this loop to execute an onload for each image in the array, and only proceed to the next iteration in the for loop once that's done. The onload is waiting for an image element to load before it executes.
for (index = 0; index < lightboxImages.length; index++) { console.log('index :' + index); // when the current image has finished loading lightboxImages[index].onload = function() { console.log('image ' + index + ' loaded.'); }; } There are only three elements in the array, and with my console.log statements I'm expecting something like this in the console:
index : 0 image 0 loaded. index : 1 image 1 loaded. index : 2 image 2 loaded. But instead I'm getting output like this:
index : 0 index : 1 index : 2 image 3 loaded. image 3 loaded. image 3 loaded. How can I prevent iteration until the onload is finished?
I also tried something like this:
// just an index variable as an example var counter = 2; toImage(i) { if (i == counter) { console.log('hooray'); } else { toImage(i++); } } toImage(0); This was causing a callstack issue that was crashing the page - I didn't include it in the original post, because I figured it was a whole separate issue, but maybe I should have in retrospect. I guess my attempt at recursion here is wrong.
image 3three times. Maybe that helps you to get a solution that doesn't need to stop iterating?++->++iyou forgoti, and want to increment it before it gets passed as a parameter.