I work with JSON and I want to count the number of elements in the response.
$.getJSON("/api/getEvents", function(data) {
$.each(data, function(key, event) {
var count = 10;
$.getJSON("/api/getUsers", function(data) {
$.each(data, function(key, event) {
alert("Value: " + count);
count++;
});
});
alert("Count: " + count);
});
});
As a result, I get:
Value: 10
Value: 11
Value: 12
...
Count: 10
Why count = 10?
It’s because ajax requests are asynchronous.
$.getJSONjust initiates a request, but javascript execution immediately continues. You can see the count if you move the alert inside the ajax callback:So after you set
var count = 10, the javascript parser then runs$.getJSON, but then immediately goes on to the next line, which in your code example alerted the “Count: 10”. Then, whenever the request finishes, it runs the callback code that increments the count and alerts theValuelines.