Possible Duplicate:
Multiple ajax calls inside a each() function.. then do something once ALL of them are finished?
Consider the following function:
function suggestSong(songs){
console.log("Suggesting song from songs:", songs);
var self = this;
var totalRelatedVideos = [];
var count = 0;
$.each(songs, function(){
count++;
self.getRelatedVideos(this.videoId, function(relatedVideos){
count--;
totalRelatedVideos = totalRelatedVideos.concat(relatedVideos);
});
});
var maxWaitTime = 1000;
var waitTime = 200;
var elapsedTime = 0;
var waitInterval = setInterval(function(){
elapsedTime += waitTime;
if(count == 0 || elapsedTime >= maxWaitTime){
clearInterval(waitInterval);
console.log("I found related videos: " + totalRelatedVideos.length);
}
}, waitTime );
};
This is how I currently implement waiting for a collection of asynchronous events to finish before executing another piece of code. There's a lot of code to do very little, though. I was wondering if there's a less obtuse way of achieving the same result?