Friday, February 23, 2024
rated 0 times [  41] [ 1]  / answers: 1 / hits: 41277  / 10 Years ago, wed, february 12, 2014, 12:00:00

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


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 setTimeouts in order to notify EventLoop?

More From » multithreading


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

[#72576] Monday, February 10, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.

Total Points: 117
Total Questions: 116
Total Answers: 116

Location: Bangladesh
Member since Sat, Jan 23, 2021
3 Years ago
maxinec questions