Sha'an
Sha'an

Reputation: 1276

Event loop or CPU, which one block this?

example:

exports.products = (req, res) => {

  let el = 1;
  for (let i = 0; i < 100000000000000; i++) {
    el += i;
  }
  console.log(el);

  ...
  ...
  ...

  res.redirect('/');
};

If I add a loop like this between my code, which one will be block (Event loop or CPU) ?

When I run this my page stays on load for a long time to process code.

At the same time, the process list looks like:

enter image description here

The page stays clogged until this process is finished.

edit: When I do operations that do not run the same function from a separate browser, the page remains collapsed.

Now is this collapsing due to event loop blocking? Or is it because my processor doesn't have the power to spare for it?

Upvotes: 0

Views: 905

Answers (1)

Mohaimin
Mohaimin

Reputation: 702

JavaScript is a single threaded language. Any synchronous action is run on that thread via Event Loop. The loop process is running on that thread. So, when the loop is still ongoing JS is using the whole thread and after it finishes, CPU usage should come down.

Your CPU is fine but your code is blocking the main thread.

You can watch this amazing video describing how Event Loop works in JavaScript

Upvotes: 4

Related Questions