Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blocking event loop when a particular function is running

Tags:

node.js

I'm assuming the answer to this is really simple.

I want to block the nodejs event loop whenever a particular function is running. The function itself might call some async things it waits on, but I don't want anything else to happen while this function is doing its thing.

thanks!

like image 279
user655489 Avatar asked Jun 05 '26 18:06

user655489


1 Answers

The way to block the event loop in node.js is to make the code synchronous:

while (true) {
  // this will block the event loop
}

Recursion is also synchronous

  function rec() {
    rec();
  }

  // This one exists with RangeError: Maximum call stack size exceeded

Using any synchronous functions like:

fs.readFileSync()
fs.writeFileSync()

// any sync functions will do

If you intend to create a timeout, that blocks everything just create a for loop to a billion and it will stop for a while.

Your request seems unnatural, maybe it is not node.js that you need. Usually, people in node are trying to make everything asynchronous.

like image 88
Alexandru Olaru Avatar answered Jun 07 '26 12:06

Alexandru Olaru