Skip to content

Instantly share code, notes, and snippets.

@Chryus
Last active January 17, 2017 19:07
Show Gist options
  • Save Chryus/baecb774761d9681f8545cf526b4aea0 to your computer and use it in GitHub Desktop.
Save Chryus/baecb774761d9681f8545cf526b4aea0 to your computer and use it in GitHub Desktop.
// prints '5' 5 times
// yikes that's not what we want
// the code runs so fast and creates only one binding of i equal to its last value, 5
for (var i = 0; i < 5; i++) {
setTimeout(function () {
console.log(i);
}, 1000);
}
// solution 1: pass setTimeout a callback with arguments
// caveat: only modern browsers support the third argument
// prints 0, 1, 2, 3, 4
for (var i = 0; i < 5; i++) {
setTimeout(print, 1000, i);
}
function print(i) {
console.log(i);
}
// solution 2: wrap SetTimeout in a closure
// works in all browsers
// prints 0, 1, 2, 3, 4
for (var i = 0; i < 5; i++) {
handleTimeout(i);
}
function handleTimeout(i) {
setTimeout(function () {
console.log(i);
}, 1000);
}
// solution 3: ES6 to the rescue! just use 'let'
// prints 0, 1, 2, 3, 4
for (let i = 0; i < 5; i++) {
setTimeout(function () {
console.log(i);
}, 1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment