Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.