JSFiddle - React, Tailwind, and code Playground

by Dominic Bosch

HTML

<div id="result"></div>

JavaScript

var el = document.getElementById('result');
var appendLog = function( res ){
    el.innerHTML += '<br>' + res;
}

appendLog("Static Argument, changed within function (expected: 0, 1, 1):");
var fStatic = function( i ) {
  var fPrintArg = function() {
    appendLog( i );
  };
  fPrintArg();
  setTimeout(fPrintArg, 100);
  i = 1;
  fPrintArg();
}; // Expected output 0, 1, 1, right
fStatic(0);

// Wait for the first example to complete
setTimeout(function(){
  appendLog("<br>Dynamic Argument, function invoked with different argument(expected: 1 (1), 1 (1)):");
  var j = 0;
  var fDynamic = function( i ) {
    j = i; // j seems to be a free variable, while i is not?
    if( i == 0 ) {
      // Delay execution in order to let i change to 1
      var fInnerQueued = function() {
        appendLog(i + ' ('+ j + ')');  //should be "1 (1)" but is "0 (1)"
      }
      setTimeout( fInnerQueued, 100);
    } else {
      appendLog(i + ' ('+ j + ')'); //  is "1 (1)" as expected
    }
  };// Expected output "1 (1)", "1 (1)" but it is "1 (1)", "0 (1)"...
  fDynamic(0);
  fDynamic(1);
}, 200);