What you're seeing is due to the REPL (Read-Eval-Print Loop) nature of the Javascript console.
You're expecting to see the result of all the setTimeout()
calls from each iteration of the loop. However, after finishing a set of statements, the JS console only prints out the return value of the most recently executed statement.
A simple display of this behavior:
Note: In these examples I'm depicting the JS console input/output instead of including executable code blocks, since the behavior being discussed is specific to interactively using the console.
> x = 4;
<- 4
> y = 5;
<- 5
> x; y;
<- 5
In the last command there are two statements, only the value of the last is printed.
If you want to print out the id's of each setTimeout()
call, you just have to explicitly perform the logging action:
> for (var i = 1; i <= 5; i++) {
console.log(setTimeout(function() { console.log('hello'); }, 100));
}
596
597
598
599
600
<- undefined
5 hello
Above you see:
- the 5 outputs from the immediately executed
console.log(setTimeout(...))
statements
- the
undefined
return value of the last console.log(setTimeout(...))
statement
- the grouped output from the 5 delayed
console.log('hello')
statements