capstonene
capstonene

Reputation: 179

why CPU-bound tasks freeze the event loop in node.js?

in wikipedia:

long-lasting computations and other CPU-bound tasks freeze the entire event-loop until completion.

i can't find out why? i also read these:

https://nodejs.org/en/docs/guides/dont-block-the-event-loop/#blocking-the-event-loop-json-dos

https://nodejs.dev/learn/the-nodejs-event-loop#the-call-stack

and more and more on event loop. but i can't find out why when a task is cpu-intensive the event loop is freezed. node.js acts asynchronously so it doesn't wait for a task and when the task is completed it callbacks. so if a task is taking a long time it shouldn't be any matter. because event loop does its job and when that task completes sends callback. so why large tasks freeze the event loop?

Upvotes: 0

Views: 498

Answers (1)

Herman Sidharta
Herman Sidharta

Reputation: 139

node.js acts asynchronously so it doesn't wait for a task and when the task is completed it callbacks. so if a task is taking a long time it shouldn't be any matter. because event loop does its job and when that task completes sends callback. so why large tasks freeze the event loop?

Event loop can't do its job if you're telling the event loop to work the task itself.

If you are spawning another Worker and have that worker do the task, then the Event loop can wait (handle other things) until that worker finished and then executing its callback, but this means you need to write the code for that, spawning workers are not done automatically.

If you are not spawning workers, then it means the task is done by the event loop, and if the task is cpu intensive (taking a lot of time to compute) then you are blocking the Event Loop from doing its job.

Upvotes: 2

Related Questions