Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
</body>
</html>
 
var result = (function(limit) {
  for (var i = 0; i < limit; i++) {
    // the setTimeout function gets added to the event stack after each iteration so therefore it's called after the current event loop. After the current event loop, the variable i has been incremented to 3.
    setTimeout(function() {
      console.log(i);
    }, 0);
  }
})(3);
// Demonstration of what happens at runtime:
result = (function(limit) {
  var i = 0;
  // First event loop
  for (i = 0; i < limit; i++) {
 
  }
  // i is equal to 3 now
  // Second and beyond event loops:
  // setTimeout callbacks get executed, outputting 3 every time
  console.log(i); // 3 three times
})(3);
// The correct way to do it using closures:
result = (function(limit) {
 for (var i = 0; i < limit; i++) {
   (function(j) {
    setTimeout(function() {
      console.log(j); // 0, 1, 2
      }, 0);
    })(i);
  }
})(3);
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
miguelmotapro
0viewers