Tarik Tarik - 3 months ago 20
Javascript Question

How is Javascript single threaded?

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
?

Answer

JavaScript (in browsers) doesn't run concurrently2.

At most one of the setTimeout callbacks can execute at a time - as there is one JavaScript execution context or "thread".

However, the "next scheduled timeout" to run is always run .. next. The "4" runs before the "2" callback because it was scheduled to run sooner. The timeouts were effectively scheduled from the same time (none of the operations were blocking), but "2" had a much longer interval.

The underlying implementation may use threads1 - but JavaScript in the same global context doesn't run concurrently and guarantees consistent and atomic behavior between all callbacks.


1 Or it may not; this can be handled without any threads in a select/poll implementation.

2 In the same context: i.e. Tab/Window, WebWorker, host Browser Control. For example, while WebWorkers are run concurrently they do so in different contexts and follow the same asynchronous model (eg. as used by timers).