I've found a posting(https://bbs.archlinux.org/viewtopic.php?id=58640) while I was googling for a similar problem as the poster's.
He was trying to figure out the fix for the code below.
for(var i=0; i<3; i++) {
req[i] = new XMLHttpRequest();
req[i].onreadystatechange = function() {
if(req[i].readyState == 4 && req[i].status == 200) {
URL = url[i];
success();
}
}
req[i].open("GET", url[i], true);
req[i].send(null);
}
The solution was
for(var i=0; i<3; i++) {
req[i] = new XMLHttpRequest();
req[i].onreadystatechange = function(index) {
return function() {
if(req[index].readyState == 4 && req[index].status == 200) {
URL = url[index];
success();
}
};
}(i);
req[i].open("GET", url[i], true);
req[i].send(null);
}
and this was because of the scoping issue with req[i]
.
I tested the value of i
inside onreadystatechange
with a similar function, and it printed 2, 2, 2, instead of 0, 1, 2.
Apparently something is happening to i
value there, but I am not sure what is happening.