Skip to content

Instantly share code, notes, and snippets.

@adong
Last active April 5, 2024 16:55
Show Gist options
  • Save adong/8d0c965e4233cfc0d30f52abb214cf5f to your computer and use it in GitHub Desktop.
Save adong/8d0c965e4233cfc0d30f52abb214cf5f to your computer and use it in GitHub Desktop.
javascript closure trap
// What is the result of the following?
for (var i=0; i<10; ++i) {
setTimeout(function() {
console.log(i);
}, 1000);
}
// using IIFE (immediately invoked function)
// with delay
for (var i=0; i<10; ++i) {
(function(j) {
setTimeout(function() {
console.log(j);
}, 1000);
})(i);
}
// without delay
for (var i=0; i<10; ++i) {
setTimeout((function(i) {
console.log(i);
})(i), 1000)
}
// wrap in a function
for (var i = 0; i < 10; i++) {
function timer(j) {
setTimeout(function() {
console.log(j);
}, j);
};
timer(i);
}
// ES6, use let instead of var
for (let i=0; i<10; ++i) {
setTimeout(function() {
console.log(i);
}, 1000);
}
// Ref: https://hackernoon.com/how-to-use-javascript-closures-with-confidence-85cd1f841a6b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment