I need to do several GET requests, and I need to define the callback function differently each time. I am doing this with a for, like this:
for (var j = 0; j < n; j++) {
let url = "http...";
httpGetAsync(url, function (responseText) {
// do things with j
});
}
But when it gets to the "do things with j" line j is always n, i.e. the value it has on the last iteration of the loop. I guess the callback functions are running after the loop has completed all its iterations, and they take the j that there is at that time.
But why is that? Shouldn't the callback function be defined using a different j each time? Shouldn't the functions use the value for j from when they were defined?
Do I need to put the callback function into a closure?
I'm pretty sure it's a matter of keeping track of the scope, but if you need the httpGetAsync function it looks like this:
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}