Nested asynchronous calls do not seem to execute as expected

Posted by Kristof Van Landschoot on Stack Overflow See other posts from Stack Overflow or by Kristof Van Landschoot
Published on 2012-06-11T16:30:45Z Indexed on 2012/06/11 16:40 UTC
Read the original article Hit count: 334

Filed under:
|
|

While trying out jQuery, I have a question that is probably a newbie mistake, but I cannot seem to find the solution. This is the code:

$.get("index.html", function() {
    var i = 0;
    for (; i < 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 " + i + "</p>";
        });
    }
});

The output seems to be

<div id='body-0'></div>
<div id='body-1'></div>
<div id='body-2'>
    <p>Hello World 3</p>
</div>

I expected the lDiv.innerHTML= code to be executed for each i, but apparently it is only executed for the last i? What am I overlooking?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery