Skip to content

Instantly share code, notes, and snippets.

@wilmoore
Last active December 29, 2015 11:39
Show Gist options
  • Save wilmoore/7665201 to your computer and use it in GitHub Desktop.
Save wilmoore/7665201 to your computer and use it in GitHub Desktop.
Avoid closure creation within a non-lexically scoped loop.
var idx = -1;
var end = 10;
function eventually(fn, timeout) {
setTimeout(fn, timeout);
}
while (++idx < 10) {
eventually(console.log.bind(console, idx));
}
for (var i=0; i<10; i++) {
 setTimeout(function() {
  console.log(i);
 }, i);
})
}
for (var i=0; i<10; i++) {
(function (i) {
setTimeout(console.log.bind(console, i), i);
})(i);
}
@wilmoore
Copy link
Author

Should print:

0
1
2
3
4
5
6
7
8
9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment