I have an issue with a function call in setTimeout in a loop.
The parameters passed to the function are the last values computed in the loop for each iteration, please see example below.
for(var i=0; i<datesYM.length; ++i) {
console.log(datesYM[i]);
var dateYM = datesYM[i];
setTimeout(function() {
myDB.markMonthsValuesAsUpdated2(myDoctorId, dateYM)
}, Math.floor(Math.random()*5001));
}
myDB.markMonthsValuesAsUpdated2 = function(myDoctorId, dateYM) {
console.log(dateYM);
[...]
Prints:
2012-01
2012-02
2012-03
2012-04
2012-05
2012-06
2012-072012-07
2012-07
2012-07
2012-07
2012-07
2012-07
2012-07