Skip to content

Instantly share code, notes, and snippets.

@ptte
Created April 7, 2014 21:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ptte/10060267 to your computer and use it in GitHub Desktop.
Save ptte/10060267 to your computer and use it in GitHub Desktop.
A somewhat non obvious scoping issue of javascripts callbacks
function test() {
for (var i=0;i < 5;i++) {
console.log('orig: '+ i);
// Crazy function with a callback here, making it async
setTimeout(function () {
// We might expect `i` to be whatever it was in the loop
// when we called the setTimeout, but it's actually not evaluated
// until the "callback" runs, and hence it will have the value
// `i` had in that exact moment.
console.log('cb: '+ i);
}, 100);
}
}
test();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment