How is Javascript single threaded?
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 Eventloop Concurrency model and Event Loop
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).