Sitemap
Jeevankumar

Jeevankumar

How Node Works

2 min readOct 3, 2024

Node.js® is a free, open-source, cross-platform JavaScript runtime environment that lets developers create servers, web apps, command line tools and scripts.

Press enter or click to view image in full size

app.js (Main Thread / Call Stack)

  • The code begins executing in the call stack:
  • console.log("Hi") gets executed, printing "Hi" to the console.
  • Next, the first setTimeout(() => {console.log("I'm from 1st TimeOut")}, 10000) is encountered. Since setTimeout is an asynchronous function, it gets handed off to the Node API (or browser's Web API in a browser environment), and the callback function (that logs "I'm from 1st TimeOut") is scheduled to run after 10 seconds.
  • Another setTimeout(() => {console.log("I'm from 1st TimeOut")}, 0) is encountered. This is also an asynchronous operation, but it is set to execute with 0 milliseconds of delay, meaning it will be added to the callback queue almost immediately after the current call stack clears.
  • console.log("End") is executed next, and it prints "End" to the console

Node API (or Web API)

    Get Jeevankumar’s stories in your inbox

    Join Medium for free to get updates from this writer.

  • The asynchronous tasks (both setTimeout calls) are now handled by the Node API (or the browser's Web API):
  • The first timeout is set to run after 10 seconds.
  • The second timeout is set to run with 0 delay, meaning the callback will be queued up almost immediately after the call stack is cleared.
  • Event Loop
  • The event loop continuously monitors the call stack and the callback queue.
  • Once the synchronous tasks (console.log("Hi") and console.log("End")) are executed and the call stack is empty, the event loop starts checking the callback queue for any pending tasks.
  • The setTimeout callback with 0 delay is now in the callback queue and will be pushed onto the call stack, where it prints "I'm from 2 TimeOut" to the console.
  • 10 seconds later, the callback from the first setTimeout (with a delay of 10,000 ms) will be executed, printing "I'm from 1st TimeOut" to the console again.
  • Output Sequence The final output sequence will be:

Key Concepts:

  • Call Stack: This is where the synchronous code is executed.
  • Node API / Web API: Handles asynchronous functions like setTimeout and waits for the delay specified to complete.
  • Event Loop: Continuously checks if the call stack is empty, and when it is, it moves tasks from the callback queue to the call stack for execution.
  • Callback Queue: Holds tasks that are waiting to be added to the call stack once it’s empty.
    Thanks
    Happy Learning :)

--

--