2
  <script language="javascript">
    // random strings
    var strings = ["How is it even possible?", "Have you ever heard about this?"];
    var WriteLine = function(s)
    {
      var end=s.length, sc=s.split("");
      for(counter = 0;counter<end;counter++)
      {
        setTimeout(function(){document.write(sc[counter]);},20);
        //                                   ^^^^^^^^^^^
      }
    }
    strings.forEach(WriteLine);
  </script>

It returns me that:

undefinedundefinedundefinedundefinedundefinedundefinedundefined

So the problem is that the variable sc is out of scope due to setTimeout function, I already have tried to use this

JustCodeIT
  • 23
  • 4
  • It's not out of scope, it just has the wrong value when the timeout happens. And no, this has nothing to do with `this`. – Bergi May 28 '17 at 20:33
  • one more thing to consider when dealing with setTimeout is `setTimeout are Executed in the Global Scope` so it will give priorities to global variables. – inrsaurabh Aug 11 '18 at 15:57

1 Answers1

1

The answer to your problem is to use Closures, you have to "save" the context. You are using a setTimeout that executes your function after some amount of time and your for loop is ,lets say, faster than 20 ms, so by the time your setTimeout executes your function counter is already s.length that's why your getting undefined

// random strings
var strings = ["How is it even possible?", "Have you ever heard about this?"];
var WriteLine = function(s)
{
  var end=s.length, 
      sc=s.split("");
  for(counter = 0;counter<end;counter++)
  {
    setTimeout((function(c){
      document.write(sc[c]);
    })(counter),20);
    //                                   
  }
}
strings.forEach(WriteLine);
AngelSalazar
  • 3,080
  • 1
  • 16
  • 22