Please take a look at this code:
$(document).ready(function() {
var urls = ['http://en.wikipedia.org/w/api.php?action=query&titles=File:Einstein2.jpg&prop=imageinfo&iiprop=url&iiurlwidth=144&format=json&callback=?', 'http://en.wikipedia.org/w/api.php?action=query&titles=File:Da_Vinci_Vitruve_Luc_Viatour.jpg&prop=imageinfo&iiprop=url&iiurlwidth=144&format=json&callback=?', 'http://en.wikipedia.org/w/api.php?action=query&titles=File:2003-32-GravitationalLens.jpg&prop=imageinfo&iiprop=url&iiurlwidth=144&format=json&callback=?'];
var x = 0;
var f = function() {
x++;
console.log(x);
};
$.getJSON(urls[0], function(json) { f(); } );
$.getJSON(urls[1], function(json) { f(); } );
$.getJSON(urls[2], function(json) { f(); } );
});
The result of this code is “1”, while I was expecting “1 2 3”.
I’ve seen solutions to this (for example, in this SO question). But I still can’t understand why the given solution should work and the code above shouldn’t.
ADDED:
When I put some code between $.getJSON calls or change console.log() to alert(), output is really “1 2 3”. When this methods are called exactly aften one another, in Chrome output becomes “1”.
ADDED:
Strange thing. Without changing the code at all I got 3 different outputs “1”, “1 2”, “1 2 3” just by reloading the page…
You may try to nest the queries like this