Skip to content

Instantly share code, notes, and snippets.

@henryspivey
Forked from prof3ssorSt3v3/7-closure.js
Last active October 30, 2019 20:49
Show Gist options
  • Save henryspivey/7ffb306cbddd66904767493eb0bcbb38 to your computer and use it in GitHub Desktop.
Save henryspivey/7ffb306cbddd66904767493eb0bcbb38 to your computer and use it in GitHub Desktop.
function f1(a) {
let b = 2;
setTimeout(function () {
console.log(a, b)
}, 1000);
}
// has a problem
// use let to scope variable inside for curly braces
function f2() {
for (var i = 0; i < 3; i++) {
setTimeout(function () {
console.log(i)
}, 1000 * i);
}
}
function f3() {
for (let i = 0; i < 3; i++) {
setTimeout(function () {
console.log(i)
}, 1000 * i);
}
}
function f4() {
for (let i = 0; i < 3; i++) {
setTimeout( (function (i) {
console.log(x)
}).bind(null,i), 1000 * i);// null is the context for the function, not important
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment