Consider this simple example:
console.log('Start');
setTimeout(function() {
console.log('First timeout');
}, 100);
setTimeout(function () {
console.log('Second timeout');
}, 2000);
var time = Date.now();
for (var i = 0; i < 2000000000; i++) {
var temp = i * i * Math.sqrt(i);
temp = temp + temp;
}
console.log(Date.now() - time);
setTimeout(function () {
console.log('Third timeout');
}, 50);
console.log('End');
The output is:
Start
1219
End
First timeout
Third timeout
Second timeout
What makes me think of the way the execution queue (stack?) is generated. Am I right that JavaScript intepreter checks the code first, generates the queue, and then starts the execution, adding functions from timeouts to the end of the queue when timeout time passes (so we have pregenerated execution queue which updates during the execution and dynamically generated timeout list)?
setTimeoutis defined) lists what steps / actions should be taken, but the engine can do it in whatever way it chooses.