What gets logged?
for (var i = 0; i < 5; i++) { setTimeout(() => console.log(i), i * 1000) }
What gets logged?
for (var i = 0; i < 5; i++) { setTimeout(() => console.log(i), i * 1000) }
A little throwback for all you old heads. This used to be everyone’s favorite JavaScript interview question.
This code will eventually log 5, 5 times.
The reason for this is because we declared our variable with var, which is function scoped. By the time our functions given to setTimeout run, i will already be 5 and every function will reference that same variable.
To fix this, use let which is block scoped and will give each iteration of our for loop its own i.
for (let i = 0; i < 5; i++) { setTimeout(() => console.log(i), i * 1000) }
or you can capture the correct value of i by passing it as an argument to the function via setTimeout’s third argument.
for (var i = 0; i < 5; i++) { setTimeout((capturedI) => console.log(capturedI), i * 1000, i) }
or you can use an IIFE to kind of do the same thing, lol.
for (var i = 0; i < 5; i++) { ((capturedI) => setTimeout(() => console.log(capturedI), i * 1000) )(i); }