Skip to content

Instantly share code, notes, and snippets.

@szydan
Created October 24, 2012 14:09
Show Gist options
  • Save szydan/3946251 to your computer and use it in GitHub Desktop.
Save szydan/3946251 to your computer and use it in GitHub Desktop.
Avoiding the Reference Problem inside loops
// borrowed from jsvascript garden
// http://bonsaiden.github.com/JavaScript-Garden/#function.closures
// In order to copy the value of the loop's index variable, it is best to use an anonymous wrapper
for(var i = 0; i < 10; i++) {
(function(e) {
setTimeout(function() {
console.log(e);
}, 1000);
})(i);
}
// The anonymous outer function gets called immediately with i as its
// first argument and will receive a copy
// of the value of i as its parameter e.
// The anonymous function that gets passed to setTimeout now has a reference to e, whose value does not get // changed by the loop.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment