Skip to content

Instantly share code, notes, and snippets.

@ifkas
Last active February 21, 2018 16:09
Show Gist options
  • Save ifkas/243ba04acfd4c2995b38ee90066eed34 to your computer and use it in GitHub Desktop.
Save ifkas/243ba04acfd4c2995b38ee90066eed34 to your computer and use it in GitHub Desktop.
IIFE example with closure
// PROBLEM
for (var i = 0; i<=3; i++) {
setTimeout(function(){
console.log("I have: " + i + " apples");
}, i*2000);
}
// > I have: 4 apples
// > I have: 4 apples
// > I have: 4 apples
// SOLUTION
// You close the variable i (index) on line 4 with the parameter of the anynomous function on line 2
for (var i = 0; i<=3; i++) {
function(i) {
setTimeout(function(){
console.log("I have: " + i + " apples");
}, i*2000);
})(i); // You call the function to execute here immediately
}
// > I have: 1 apples
// > I have: 2 apples
// > I have: 3 apples
// > I have: 4 apples
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment