var data = [{offset: 2000, str:'foo'}, {offset: 4000, str:'bar'}];
for (var i=0; i<data.length; i++) {
var x = data[i];
setTimeout(function(){printStuff(x.str)}, x.offset);
}
function printStuff(str) {
console.log(str);
}
I was expecting to get printStuff('foo') at 2000 ms offset and printStuff('bar') at 4000 ms offset but instead it prints 'bar' both times. I've no idea what's going on, help please.
printStufffinally runs,xhas been reassigned to{offset:4000,str:'bar'}