title: jquery deferred in loop for sequential processing
body: <p>The goal: loop through an array of urls ONE AT A TIME, letting them load completely using postMessage to determine when finished (some of the pages will take a long time) </p>
  
  <p>Implemented this, but it's not working quite right: <a href="https://stackoverflow.com/questions/28552302/jquery-deferred-in-for-loop">jquery deferred in for loop</a></p>
  
  <p>Implemented this, and it's working, but not in a loop because the javascript only opens the last window: <a href="http://davidwalsh.name/window-postmessage" rel="nofollow noreferrer">http://davidwalsh.name/window-postmessage</a></p>
  
  <pre><code>function scrape(url){
      var deferred = new $.Deferred();
        var myPopUp = window.open(url,'myWindow');
        setInterval(function(){
          var message = 'Hello!  The time is: ' + (new Date().getTime());
          console.log('Scraper Launcher:  sending message:  ' + message);
          myPopUp.postMessage(message,domain);//send the message and target URI
          },6000);
  
          //listen to holla back
          window.addEventListener('message',function(event) {
                  if(event.origin !== domain) return;
                  console.log('received response:  ',event.data);
                  if(event.data == 'You were successful!'){
                     console.log('closing child window');
                     myPopUp.close();
                     deferred.resolve('Success');
                  }else{
                     console.log('oh dear, FAILURE: ' + urls[i]);
                     deferred.resolve('Failure');
                  }
               },false);
  
  
      return deferred.promise();
  }
  
      var urls = [domain +"/url1",domain +"/url2"];
  
     $("#launch_windows").click(function(){
        console.log('launching');
        for (i = 0; i &lt; urls.length; i++) {
           (function(i){
              console.log('NOW i is ' + i + ' and url is ' + urls[i]);
              $.when(scrape(urls[i])).then(function(results){
                 console.log('DONE (' + results + ')with ' + urls[i]);
              });
            })(i);
        }
      });
  </code></pre>
  
  <p>And if this is totally horrible logic and code, I'm all ears for suggestions.</p>