Last active
February 21, 2018 16:09
-
-
Save ifkas/243ba04acfd4c2995b38ee90066eed34 to your computer and use it in GitHub Desktop.
IIFE example with closure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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