Possible Duplicate:
Passing functions to setTimeout in a loop: always the last value?
I know I need to use closure to deal with problem, but I'm not sure how; I have function, where I get data from server:
function loadGraph(chartDataStreams) { //length of chartDataStreams is two
initCharts(); //init charts area
for (c in chartDataStreams) {
var chartData = [];
alert(c); // says : 0, then 1
getDataFromServer(chartDataStreams[c].x, chartDataStreams[c].y,function (data) {
for (d in data.datapoints) {
var item = { date: new Date(data.datapoints[d].at), value:data.datapoints[d].value };
chartData.push(item);
}
alert(c); // says: 1 then 1
updateGraphData(chartData);
});
}
}
in this function I need to call updateGraphData, which updates graph data provider with chartData. Problem is that in chartData I don't have just the actual data but also the data from previous loop cycle. I think this the right place to use closures, but I'm not sure how.. Do you have any ideas?
//edit: I put the declaration of chartData by mistake outside the getDataFromServer function, but I've got still one problem: check the edited code. From the second alert I want to say 0 and 1, not just 1,1