title: Variable scope in nested functions in Javascript
body: <p>I have looked through countless examples which indicate that this is supposed to work, but it does not. I was wondering if someone could have a look and indicate why. I am trying to access the variable "dia" from within the setTimeout function, but it always returns undefined:</p>
  
  <pre><code>var dialogue = new Array();
  dialogue[0] = 'Hi there Mo, I am Mark. I will be guiding through the game for you today';
  dialogue[1] = 'Hey there Mark, how you doing?';
  dialogue[2] = 'I am doing fine sweetie pie, how about yourself?';
  dialogue[3] = 'I am good too, thanks. Are you ready for today, i.e. the big day?';
  dialogue[4] = 'I certainly am, Mark';
  var dcount;
  var loopDelay;
  var diatext;
  for(dcount = 0; dcount &lt;= dialogue.length; dcount++)   {
      var dia = dialogue[dcount];
      if(dcount == 0) { loopDelay = 0; } else {
          loopDelay = ((dia.length)*1000)/18;
      }
      setTimeout(function() {
          alert(dia);
          diatext = Crafty.e('2D, DOM, Text')
              .text(dia)
              .textFont({ size: '11px', weight: 'bold' })
              .attr({ x: 200, y: 150, w:400, h:300})
              .css();
      }, loopDelay);
  }
  </code></pre>