I've looked at this questions, but I'm still stuck at this JavaScript closure inside loops – simple practical example
Here's my code
template[prop['Name']] = [];
var processedCounter = -1;
$.each(prop.Properties, function (key, value) {
console.log(processedCounter + 'outside');
$.getJSON(value['Url']).done(function (jsres) {
console.log(processedCounter + 'inside');
var numItems = jsres[itemCount].length;
if (template[prop['Name']].length == 0) {
console.log('this should only be printed once');
for (var i = 0; i < numItems; i++) {
template[prop['Name']].push({});
}
}
processedCounter += 1;
});
});
There's several issues. First it that it prints the message 'this should only be printed once' two times. Second is that the value of processedCounter has to be -1 instead of 0, because the value is increased at the wrong time.