Skip to content

Instantly share code, notes, and snippets.

@ronen-e
Created April 5, 2017 05:15
Show Gist options
  • Save ronen-e/bdd2a0fbe6a61942dea25d908ac2be56 to your computer and use it in GitHub Desktop.
Save ronen-e/bdd2a0fbe6a61942dea25d908ac2be56 to your computer and use it in GitHub Desktop.
Create new scope in javascript
function func() {
for (var i = 0; i < 10; i++) {
setTimeout(function() {
console.log('i:' + i);
}, 0);
}
}
// func();
function solution1() {
for (let i = 0; i < 10; i++) {
setTimeout(function() {
console.log('i:' + i);
}, 0);
}
}
// solution1();
function solution2() {
for (var i = 0; i < 10; i++) {
var fn = function(index){ console.log('i:' + index);};
setTimeout(fn.bind(null, i), 0);
}
}
// solution2();
function solution3() {
for (var i = 0; i < 10; i++) {
var fn = function(index){ console.log('i:' + index);};
(function(index) {
setTimeout(() => {fn(index);}, 0);
})(i);
}
}
// solution3();
function solution4() {
for (var i = 0; i < 10; i++) {
try {
throw i;
} catch(index) {
setTimeout(function() {
console.log('i:' + index);
}, 0); }
}
}
// solution4();
function solution5() {
for (var i = 0; i < 10; i++) {
var fn = function(index){ console.log('i:' + index);};
setTimeout(fn, 0, i);
}
}
// solution5();
var solution6fn = function (index){ console.log('i:' + index);};
function solution6() {
for (var i = 0; i < 10; i++) {
setTimeout("solution6fn(" + i + ")", 0);
}
}
//solution6();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment