Skip to content

Instantly share code, notes, and snippets.

@awilson28
Last active March 11, 2018 17:42
Show Gist options
  • Save awilson28/a128e1e508b88adcfa11 to your computer and use it in GitHub Desktop.
Save awilson28/a128e1e508b88adcfa11 to your computer and use it in GitHub Desktop.
//run this in your console
for (var i = 0; i <= 3; i++) {
  setTimeout(function(){
    console.log(i); 
  }, 0); 
} 



/* fixing this with an Immediately Invoked Function Expression (IIFE)
The IIFE creates a new scope for each iteration, 
providing the callback in setTimeout with a new variable i that is 
mapped to the right per-iteration value */

for (var j = 0; j <= 3; j++) {
  (function(k){
    setTimeout(function(){
      console.log(k); 
    }, 0)
  })(j) 
} 



/* above, we define an IIFE that takes a parameter k and then console.log's that k
and then we invoke that IIFE with j: the IIFE closes over j so that the 
callback function has a copy of j at 0, 1, 2, and 3. Note that we can also
just keep j everywhere as shown in the code directly below: */

for (var j = 0; j <= 3; j++){
  (function(j) {
    setTimeout(function() {
      console.log(j); 
    }, 1000)
  })(j)
}

//We can achieve the same functionality like so: 

for (var i = 0; i <= 3; i++) {
  (function() {
    var j = i; 
    setTimeout(function() {
      console.log(j)
    }, 1000)
  })();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment