I'm reading You Don't Know JS book series.
In Ch.5 of Scope & Closure title of this book, there's this for loop i'm unable to understand
for (var i=1; i<=5; i++) {
setTimeout( function timer(){
console.log( i );
}, i*1000 );}
It prints 6 in console 5 time after 1s interval. Even author is trying to explain why it's happening but i'm unable to get what he's trying to say.
You can find this code with explanation here: https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch5.md
Head to 'Loop + Closure' section on the page you'll find this code.
Can anyone please explain me this in simple language?? Why it print 6 in console for 5 time instead of 1, 2,..., 5 after 1sec interval.
Thanks in Advance for your time & effort.