Reputation: 696
I have this function that is supposed to check for the existence of images up to the point where they stop appearing, based on their title:
function LoadPictures(){
const PIC_MAX = 12;
var i = 1;
while (i <= PIC_MAX){
$.ajax({url: "pic" + i + ".jpg",
type: "HEAD",
success: function(){
$("body").append("<img src='pic" + i + ".jpg' />");
},
error: function(){
i = PIC_MAX + 1;
}
});
i++;
}
}
And yet, when I run the function, all I get are blank boxes. I know the loop correctly counted the existing images based on the amount of boxes appearing, but it failed to load them. Why is that?
Upvotes: 1
Views: 81
Reputation: 102763
It's because the callback is asynchronous, so the value of i
will likely be the last value in the loop every time the callback executes. Consider the following example (DEMO):
var length = 10;
var url = window.location;
for (i=0 ; i<length ; i++) {
$.get(url, function(result) {
console.log(i);
});
}
Here, the value logged for i
will not be 1 through 10, because i
is a local variable that continues to get updated while the server sends a response.
You can use a technique called "currying" to get around this. Wrap your callback function in another function, which passes in the current value of i
immediately (DEMO):
success: (function(i){
return function() {
$("body").append("<img src='pic" + i + ".jpg' />");
}
})(i),
Upvotes: 5