title: I usually wait for a collection of asynchronous events to finish using a setInterval poller. Is there a better way?
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/8726046/multiple-ajax-calls-inside-a-each-function-then-do-something-once-all-of-the">Multiple ajax calls inside a each() function.. then do something once ALL of them are finished?</a>  </p>
  </blockquote>
  
  
  
  <p>Consider the following function:</p>
  
  <pre><code>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 &gt;= maxWaitTime){
              clearInterval(waitInterval);
              console.log("I found related videos: " + totalRelatedVideos.length);
          }
      }, waitTime );
  };
  </code></pre>
  
  <p>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?</p>