Show Async Handling

Template for writing a fiddle which can display a result, rather than having to output it to the console.

by Luis Perez

HTML

<pre id="output"></pre>

JavaScript

console.log = function() {
  var args = Array.prototype.slice.call(arguments, 0);
  document.getElementById('output').innerHTML += args.join(" ") + "\n";
}

function one() {
console.log('One')
  //Non-Async (Blocking for loop)                
  for (var i = 0; i < 4; i++) {
    console.log(i)
  }
  console.log(i)
}

// Set timeouts within the construct of var binding to global variable 'i'
function two() {
console.log('two')
  for (var i = 0; i < 4; i++) {
    setTimeout(function() {
      // By the time this executes the value of i is 4, which caused it to break out of the loop.  
      console.log(i); // Could be 0,1,2,3 -> 1,2,2,4 -> .... You can't fully control what the event loop does(Manipulating process.nextTick is dangerous.)
    }, 0);
  }
  // Reaches here before any of the setTimeouts are triggered
  console.log('Value of i: ', i) // Unexpected behavior because of the scope of the variable i being set globally.
}

// SetTimeout async calls with Let.
function three() {
  for (let i = 0; i < 4; i++) {
    setTimeout(function() {
      // i does not exist in the global scope, everytime the setTimeout function is called it's binding to it's current local definition of the variable 'i'
      console.log(i); // Will always product 0,1,2,3    
    }, 0);
  }

  console.log('Value of i within the let construct:(Suppressing the error ')
  try {
    console.log(i);
  } catch (e) {
    console.log(e)
  }
}

one();
setTimeout(two, 1000)
setTimeout(three, 2000)