javascript - Nested asynchronous calls do not seem to execute as expected -
while trying out jquery, have question newbie mistake, cannot seem find solution. code:
$.get("index.html", function() { var = 0; (; < 3; i++) { var ldiv = document.createelement('div'); ldiv.id = 'body-' + i; document.getelementbyid('body').appendchild(ldiv); $.get('index.html', function(data) { ldiv.innerhtml = "<p>hello world " + + "</p>"; }); } });
the output seems be
<div id='body-0'></div> <div id='body-1'></div> <div id='body-2'> <p>hello world 3</p> </div>
i expected ldiv.innerhtml=
code executed each i, apparently executed last i? overlooking?
this happens because loop completes (i
2) before of callbacks fired.
@thecodeparadox's solution works, serializes http requests. (makes them fire one-at-a-time.) allows requests execute in parallel, , quicker:
for (var = 0; < 3; i++) { var ldiv = document.createelement('div'); ldiv.id = 'body-' + i; document.getelementbyid('body').appendchild(ldiv); $.get('index.html', function(i,ldiv) { // current iteration's `i` , `ldiv` captured... return function(data) { ldiv.innerhtml = "<p>hello world " + + "</p>"; } }(i,ldiv)); // ...by passing them argument self-executing function }
Comments
Post a Comment