I was playing with jQuery and async calls last night and found an unusual issue. I wanted to run multiple Ajax calls inside a loop. I wrote the below (where rand.php just sleeps for a second and returns a random number). Somewhat surprisingly it executes synchronously and takes 20 seconds or so to finish.
$(document).ready(function () {
$([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]).each(function() {
var number = this;
$.get("rand.php", function(data) {
$('#'+number).html(data);
});
});
});
The PHP code is as follows,
<?php
sleep(1);
echo rand();
?>
I was thinking this is clearly wrong as the async calls should be no blocking and return almost in parallel. After much playing around (assuming it was a server issue) I discovered that appending anything to the URL to make it look like it was different worked as expected. That is it returned in 3 seconds or so (6 or so calls at a time).
$(document).ready(function () {
$([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]).each(function() {
var number = this;
$.get("rand.php?"+number, function(data) {
$('#'+number).html(data);
});
});
});
I don't suppose a jQuery/Javascript Guru can explain this behavior? Is it some browser limitation? Why is it that only when the URL's are different that it runs as I would expect?
EDIT - Rather then reply, this was using Chrome (whatever the latest is) and Firefox 5/6. I did try it in IE which did cache it, so ignored that and focused on Chrome. Interesting the first one works as expected in IE9 on the first page load, but then just displays cached results when reloaded.