I have this code :
for (var i = 0; i < result.length; i++) {
// call a function that open a new "thread"
myObject.geocode({ param1: "param" }, function(results, status) {
alert(result.title[i]);
});
}
The .geocode function (that is not mine, so I can’t edit) open a new “thread” of execution.
When I try to print title on each step, I get always the last possible value of i.
How can I keep a reference to the right value of i for each iteration?
You can create a closure within the loop;
So here we’re creating a function;
… which accepts one parameter named
i, and launches the geocode request. By adding the(i)to the end of the declaration of a function expression, we run the function straight away and pass it the current value ofi.It doesn’t matter that a variable
ialready exists at a higher scope than the closure, because the local declaration ofioverrides it. Either the variable we pass to the closure, or the name the closure calls the variable could be different;Alternately you could also extract the logic to another function (I prefer it, but it’s less cool):
The problem is down to the same
ivariable being used by the callback functions; which, as you’ve discovered, has moved on by the time the callback executes. Both of the above solutions creates another variable for each iteration, and it is this that the callback operates on.