1

This code below is extracted from You don't know "JavaScript : Scopes and Closures" book by Kyle Simpson.

for (var i=1; i<=5; i++) {
    setTimeout( function timer(){
        console.log( i );
    }, i*1000 );
}

The author talks about how it will print the the number 6 five times every second but doesn't quite explain why.

From my point of view, I see the function timer() inside function setTimeout() and also know that the timer() covers the scope of its outer function too. If the code had something extra like this:

for (..) {...};
var foo = setTimeout(something);
foo();

In this case, foo() has the function timer() stored in it as a value (function object I suppose). So upon execution, it prints out whatever code is inside timer() function.

However, in the example given by the author there are no such steps and I can't quite get my head around over how the code is working internally and why it print 6 five times. The for-loop is confusing me even more. I would greatly love to how the process is working internally inside Javascript hood.

Bijay Timilsina
  • 757
  • 2
  • 10
  • 25
  • 1
    The reason it prints `6` five times, is because the loop happens **now**, the console log inside the timer happens **later**, when the loop has finished, and the value of `i` is whatever it was set to last, in this case `6`. – adeneo Nov 11 '16 at 22:54

0 Answers0