Could anyone explain how to wait for an event to finish to move forward on the next iteration inside a for loop? For example:
for ( i=0; i < item.length; i++ ) {
$(video[i]).on('loadeddata', function() {
// do my stuff
})
}
Now, with this code I'm just adding an event listener to each video in the right order but obviously they will not load in this way. They will do my other stuff when they'll finish loading, and 'cause it's unpredictable, this ruins the order of the showed item on the page. So, how can I make the for loop to wait until the event finishes it's own stuff, before it goes to the next iteration?
EDIT: I'm adding more informations as requested. I actually have an object, containing HTML Elements. This object is retrieved with var items = $('.db-gallery-item'). The values of this object as I said are <div> elements, containing a container <div> with two elements inside for images (<img> and <a>) and a single <video> element for videos. Loading them i have to mantain their order, and so is required to wait for each element to load for make it visible and go working on the next.
SOLVED: Managed to solve this with the solution proposed by palash. This is the final code i used.
if(i_length > 0) {
(async function() {
for (i = 0; i < i_length; i++) {
var item = $(items[i]);
if($(item).find('.dbg-video').length == 1) {
var video = $(item[0]).children().children();
if(video[0].readyState > 3) {
item.removeClass('db-are-unloaded');
$grid.masonry('appended', $(item));
}
else {
await new Promise(resolve => video[0].addEventListener('loadeddata', resolve));
$(item[0]).removeClass('db-are-unloaded');
$grid.masonry('appended', $(item[0]));
}
}
else if($(item).find('.db-gallery-image').length == 1) {
await new Promise(resolve => $(item[0]).imagesLoaded().done(resolve));
$(item[0]).removeClass('db-are-unloaded');
$grid.masonry('appended', $(item[0]));
}
}
}());
};
Here's a JSFiddle working example.