Possible Duplicate:
Passing functions to setTimeout in a loop: always the last value?
I have the following code:
var points = [{
id1 : 1,
id2 : 9,
lat : 44,
lng : 24
},{
id1 : 2,
id2 : 7,
lat : 13,
lng : 29
}];
when I am trying to create timeouts for every object in the array points, it updates only the last element
for (var i in points){
setInterval(function(){
drivePoint(points[i], i)
}, 1000);
}
where drive point is the function that makes ajax request:
function drivePoint(point, i){
$.ajax({
type: "POST",
url: 'url',
data: points[i]
}).done(function(o){
var data = $.parseJSON(o);
points[i].lat = data['lat'];
points[i].lng = data['lng'];
});
}
idea of drivePoint is to update the coordinate of a given point, but the problem is that it updates only the last one, nevertheless how many objects are in points variable if instead of for (var i in points) loop to write this separately
setInterval(function(){
drivePoint(points[0], 0)
}, 1000);
setInterval(function(){
drivePoint(points[1], 1)
}, 1000);
everything works fine
Can not understand where is the problem