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:

Pasted image 20230814102911.png

So happening like this:

  1. console.log("run")
  2. run shortWaitFunction, which use setTimeout, therefore it will be run in parallel from the WebAPI
  3. console.log("run2")
  4. run longWaitFunction() which use setTimeout, therefore will be run paralllely from the WebAPI
  5. run the Promise function which trigger await(), 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.
  6. It see the line while (true), it adds to the top of the stack
  7. run console.log("run3") in main thread
  8. run console.log("run4") in main thread
  9. run while (true) on the top of the stack
  10. 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.