For a photogalery I load a file (via ajax) which returns an array of src’s of the images I want to display. They HAVE TO be displayed in the exact order the ajax call returns.
I’m using a for-loop with the .load() function inside it, but that way it’s not synchronised. If I output the value of i inside the .load() function, it doesn’t go 0, 1, 3, 4, etc. but 0, 3, 2, 4, etc.
The simplified version of my code:
$.get('photostack.php', {album_name:album_name} , function(data) {
var items_count = data.length;
for(var i = 0; i < items_count; ++i){
var item_source = data[i];
var cnt = 0;
$('<img />').load(function(){
var $image = $(this);
++cnt;
console.log(i);
$ps_container.append($image);
}).attr('src',item_source).attr('class',i);
}
},'json');
console.log(i) now gives the wrong order. It should be perfectly ascending.
I have tried a lot of things. Delaying every load 100 ms, using an object as variable for cnt/i, etc. but none of them worked.
Not sure I really get it, but maybe something like this will work: