0

I understand closures but I don't understand how this example works:

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

In this example it logs 6 six times with a value of six. I understand this is due to closures. However, I don't understand how. Any help would be appreciated.

Kewl
  • 3,327
  • 5
  • 26
  • 45
  • Duplicate [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – abhishekkannojia Mar 30 '17 at 12:30
  • the value of `i` is 6 by the time `console.log` has fired – Joe Lissner Mar 30 '17 at 12:33
  • Don't forget that JS does not have block scopes, and all six closures you created close over the same `i` variable – Bergi Mar 30 '17 at 13:50

0 Answers0