How is Javascript single threaded? How is Javascript single threaded? javascript javascript

How is Javascript single threaded?


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


Javascript uses something called Eventloop for Asynchronous calls.The setTimeout is pushed to EventLoop since it is a callback. and the main thread continues to execute. Once the main completes, Then the EventLoop pushes the data to the main stack. Ex:

console.log("1");setTimeout(function(){console.log("2");},0);console.log("3");setTimeout(function(){console.log("4");},1000);

When the timeout is 0, then the output of the code will be,

1 3 2 4

Since it first executes the calls of the Main and then brings back data from EventloopConcurrency model and Event Loop


Javascript executes each line in sequence.

So you told js:

  • write 1: js writes 1
  • wait 3 seconds and then write 2: ok I'll wait 3 seconds...now what?
  • write 3: ok I'll write 3, by the way, the 3 seconds is not up.
  • wait 1 second and then write 4: ok I'll wait 1 second...

then js waits .99999 seconds ... and writes 4

then waits some more and writes 2