Asynchronous Constructor Instantiation and DOM Insertion Within Loop

Asynchronous Constructor Instantiation and DOM Insertion Within Loop

Hey All,

How can I best execute code with an async callback in a loop? At this point I'm using a callback from a setTimeout zero. Meh.

For example, here I instantiate 1000 Button objects from the Button() constructor function, and insert them into the #pageContent div.

  1. // Happily adds buttons to page one at a time, as they are instantiated
  2. var $pageContent = $('div#pageContent');
  3. for (var count = 0; count < 1000; count++) {
  4.       setTimeout( function() {
  5.             var myButton = new Button();
  6.             $pageContent.append(myButton);
  7.       }, 0 );
  8. }

A synchronous attempt locks up the browser for a few seconds, and then dumps all the buttons to the screen at once; presumably, because the loop is completes long before the buttons are instantiated. Please correct me if I'm wrong.

  1. // locks up browser for a few seconds, and dumps all buttons to the page at once.
  2. var $pageContent = $('div#pageContent');
  3. for (var count = 0; count < 1000; count++) {
  4.       (function(){
  5.             var myButton = new Button();
  6.             $pageContent.append(myButton);
  7.       }());
  8. }

Thank you for your help.

Sincerely,
Keith :^)