Tarik Tarik - 1 year ago 62
Javascript Question

How is Javascript single threaded?

I have a question about the single threaded nature of Javascript.


The result of this code is
1 3 4 2
. As you see,
comes after
which makes me wonder that in a single threaded environment shouldn't
have come after
? If not, then how come JS knows the second
should finish before the first one? Shouldn't there be two threads which work concurrently to complete the two
s in order to notify

Answer Source

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).