Consider the following code:
for (var i = 1; i <= 5; i++) {
setTimeout(function printNumbers() {
console.log(i);
}, i * 1000);
}
I know that it is not a good practice to define functions inside a loop but it is not the main problem. I was expecting this code to print 1,2,3,4,5 a second apart from each other but it print 6 five times a second apart. My two questions are:
Why it is not printing the desired result? How does the counter even reach 6 when my condition is to stop at 5