How can I delay running a function until after jQuery get() has finished

Viewed 29

I'm using this piece of code inside of a for loop to append some content to a div:

$.get("./" + i + "/block.html", function(data){ 
    $(data).appendTo("#id");
});

After that, I'm using this piece of code to make the added content clickable, there's a .person div inside every block.html:

$(".person").click(function () { 
    $(this).toggleClass("large");
});

This second piece of code has no effect because the first piece runs asynchronously. So the content hasn't been appended yet by the time it runs. How can I delay it until it has been?

2 Answers

One way of doing it is with a counter and if all data is loaded add it, this also ensures the data is added in the right order. The keyword let (instead of var) is very important, otherwise you have to use closures to capture the current value of i.

function addData(n) {
    let count = 0, content = []
    for (let i = 0; i < n; i++) {
        $.get("./" + i + "/block.html", function(data) { 
            content[i] = data // using var i would be n here
            if (++count == n) {
                for (let j = 0; j < n; j++)
                    $(content[j]).appendTo("#id")
                $(".person").click(function () { 
                    $(this).toggleClass("large")
                })
            }
        })
    }
}

I wanted to add a simpler solution I found.

You can run

jQuery.ajaxSetup({async:false});

at the start to make the get() functions run synchronously. If you need them to run asynchronously for another part of the page, just run

jQuery.ajaxSetup({async:true});

to switch back to asynchronous mode afterward.

Source

Related