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
Wrap the body in its own self-executing function to force a new scope:
Without this, every function created in the loop closes over the same instance of
dateYM, which has the value of the last iteration by the time any of those functions execute. Since JavaScript has function scope, the wrapper function creates a newdateYMon each iteration, so that each new function passed tosetTimeouthas its own instance.