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.
- // Happily adds buttons to page one at a time, as they are instantiated
- var $pageContent = $('div#pageContent');
- for (var count = 0; count < 1000; count++) {
- setTimeout( function() {
- var myButton = new Button();
- $pageContent.append(myButton);
- }, 0 );
- }
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.
- // locks up browser for a few seconds, and dumps all buttons to the page at once.
- var $pageContent = $('div#pageContent');
- for (var count = 0; count < 1000; count++) {
- (function(){
- var myButton = new Button();
- $pageContent.append(myButton);
- }());
- }
Thank you for your help.
Sincerely,
Keith :^)