Skip to content

Instantly share code, notes, and snippets.

@crudbetter
Created December 11, 2014 11:48
Show Gist options
  • Save crudbetter/09d042d486e1a1b39a91 to your computer and use it in GitHub Desktop.
Save crudbetter/09d042d486e1a1b39a91 to your computer and use it in GitHub Desktop.
JavaScript closure of iterator index
var foos = [
{ bar: 1 },
{ bar: 2 }
];
for (var i = 0; i < foos.length; i++) (function(index) {
setTimeout(function() {
console.log(foos[index].bar);
}, 1);
})(i);
// rather than
for (var j = 0; j < foos.length; j++) {
setTimeout(function() {
console.log(foos[j].bar);
}, 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment