0

I get the response from /route1 until /route2 logs "ROUTE2".

But I studied that nodejs puts functions like setTimeout() in external threads and the main thread continues to work. Shouldn't the for loop executed in an external thread?

app.get("/route1",(req,res)=>
{
    res.send("Route1");
});

app.get("/route2",(req,res)=>
{
    setTimeout(()=>
    {
        console.log("ROUTE2");
        for(let i=0;i<1000000000000000;i++);
        res.send("Route2");
    },10000);
})
Rajat Aggarwal
  • 392
  • 3
  • 16

1 Answers1

0

Node.js uses an Event Loop to handle Asynchronous operations. And by Asynchronous operations I mean all I/O operations like interaction with the system's disk or network, Callback functions and Timers(setTimeout, setInterval). If you put Synchronous operations like a long running for loop inside a Timer or a Callback, it will block the event loop from executing the next Callback or I/O Operation.

In above case both /route1 and /route2 are Callbacks, so when you hit them, each callback is put into the Event Loop.

Below scenarios will give clear understanding on Asynchronous nature of Node.js:

  1. Hit /route2 first and within 10 Seconds(Since setTimeout is for 10000 ms) hit /route1

In this case you will see the output Route 1 because setTimeout for 10 secs still isn't complete. So everything is asynchronous.

  1. Hit /route2 first and after 10 Seconds(Since setTimeout is for 10000 ms) hit /route1

In this case you will have to wait till the for loop execution is complete

for(let i=0;i<1000000000000000;i++);

because a for loop is still a Synchronous operation so /route1 will have to wait till /route2 ends

Refer below Node.js Guides for more details:

Blocking vs Non-Blocking

The Node.js Event Loop

Vishal-L
  • 1,307
  • 1
  • 9
  • 16