Here is the code that loads all five images successfully:
for(i=0; i<5; i++) {
(function() {
var oReq = new XMLHttpRequest();
var r = "images/"+i+".jpg";
oReq.open("GET",r, true);
oReq.responseType = "arraybuffer";
oReq.send();
oReq.onload = function(oEvent) {
var blob = new Blob([oReq.response], {type: "image/jpg"});
var x = window.URL.createObjectURL(blob);
var img = new Image();
img.src = x;
img.width = 100;
$("#someDiv").append(img);
};
})();
}
Here is the code that loads only the last image:
for(i=0; i<5; i++) {
var oReq = new XMLHttpRequest();
var r = "images/"+i+".jpg";
oReq.open("GET",r, true);
oReq.responseType = "arraybuffer";
oReq.send();
oReq.onload = function(oEvent) {
var blob = new Blob([oReq.response], {type: "image/jpg"});
var x = window.URL.createObjectURL(blob);
var img = new Image();
img.src = x;
img.width = 100;
$("#someDiv").append(img);
};
}
Why does the callback to an asynchronous function in a for loop only work when the code is placed in a function rather than placed directly inside of the loop?