0

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?

Community
  • 1
  • 1
Sean Anderson
  • 27,963
  • 30
  • 126
  • 237
  • 3
    Yes, you can use deferred objects (http://api.jquery.com/category/deferred-object/). Have a look at these questions for an example: http://stackoverflow.com/q/3405218/218196, http://stackoverflow.com/q/8726046/218196. – Felix Kling Oct 13 '12 at 17:15
  • What is the code for getRelatedVideos? – Explosion Pills Oct 13 '12 at 17:23

0 Answers0