Javascript Is Single Thread
For example this code:
const longWaitFunction = async () => {
// putting await here so that main stack can run
await new Promise(resolve => {
setTimeout(resolve, 0);
});
while (true) {
// This loop will still run indefinitely
}
}
const shortWaitFunction = async () => {
setInterval(() => console.log("short wwait"), 2000)
}
(async () => {
console.log("run")
shortWaitFunction()
console.log("run2")
longWaitFunction()
console.log("run3")
console.log("run4")
})()
The log will be
run
run2
run3
run4
Note that shortWaitFunction()
and longWaitFunction()
doesn't print because the Web API
is blocking the async function so there is nothing getting in the event loop.
So the architecture looks similar to this:
So happening like this:
console.log("run")
- run
shortWaitFunction
, which usesetTimeout
, therefore it will be run in parallel from the WebAPI console.log("run2")
- run
longWaitFunction()
which usesetTimeout
, therefore will be run paralllely from the WebAPI - run the
Promise
function which triggerawait()
, so the javascript runtime knows to pull from the event loop queue later on when it's ready. It goes back to execute from the main call stack. - It see the line
while (true)
, it adds to the top of the stack - run
console.log("run3")
in main thread - run
console.log("run4")
in main thread - run
while (true)
on the top of the stack - After this it will hang
- There might be stuff in the event queue, but since JS runtime is already hung, it wouldn't be able to pull from the queue.