I see that you made the edit!
But that is not actually what happens when you run the code.
The code you wrote prints 0-4 (all indexes) after 2000ms all at once.
I was curious how to make a loop that prints out each index, one at a time, according to the setTimeout value.
Maybe this isn't possible using a for loop.
I hope that makes sense!!
They print all at once because all setTimeout starts at same time and for all setTimeout 1 second passes at same time. What you want can be achieved by passing timeout values to 1000, 2000, 3000....
Following code will give you that output:
for(var i=0; i<5; i++) { setTimeout((function(index) { return function() { console.log(index); } }(i)), 1000 * i) }
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I see that you made the edit!
But that is not actually what happens when you run the code.
The code you wrote prints 0-4 (all indexes) after 2000ms all at once.
I was curious how to make a loop that prints out each index, one at a time, according to the setTimeout value.
Maybe this isn't possible using a for loop.
I hope that makes sense!!
They print all at once because all setTimeout starts at same time and for all setTimeout 1 second passes at same time. What you want can be achieved by passing timeout values to 1000, 2000, 3000....
Following code will give you that output: