I have a question about the single threaded nature of Javascript.
console.log("1");setTimeout(function(){console.log("2");},3000);console.log("3");setTimeout(function(){console.log("4");},1000);
The result of this code is 1 3 4 2
. As you see, 4
comes after 2
which makes me wonder that in a single threaded environment shouldn't 2
have come after 4
? If not, then how come JS knows the second setTimeout
should finish before the first one? Shouldn't there be two threads which work concurrently to complete the two setTimeout
s in order to notify EventLoop
?