Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Node.js, does setTimeout() block the event loop?

If I have a simple setTimeout() function, and set it for 10 seconds...

The the entire server is dead inside those 10 seconds??? Is this true? That's what I heard.

like image 443
TIMEX Avatar asked Jan 21 '12 05:01

TIMEX


People also ask

How does setTimeout work in event loop?

It's important to note that setTimeout(…) doesn't automatically put your callback on the event loop queue. It sets up a timer. When the timer expires, the environment places your callback into the event loop, so that some future tick will pick it up and execute it.

How are event loops blocked?

The Event-loop is single-threaded Also known as the “one instruction to block them all” factor. Indeed in Node. js you can block every request just because one of them had a blocking instruction. A good review of your code should always start with a distinction between blocking and non-blocking code.

Is setTimeout blocking?

Explanation: setTimeout() is non-blocking which means it will run when the statements outside of it have executed and then after one second it will execute. All other statements that are not part of setTimeout() are blocking which means no other statement will execute before the current statement finishes.

How does setTimeout work in Nodejs?

The setTimeout() executes the function passed in the first argument after the time specified in the second argument. The setTimeout function doesn't block other code and the rest of the code is executed and after a specified time the code inside setTimeout function is executed.


1 Answers

The answer is no. What your link Node.js: How would you recreate the 'setTimeout' function without it blocking the event loop? showed was not a setTimeout blocking the event loop it was a while loop that deliberately blocks the event loop. If you want your server to be fast you do not want to block the event loop. An asynchronous callback such as setTimeout will work great.

Are you trying to block for some reason (like testing or something?)

like image 169
Jamund Ferguson Avatar answered Oct 02 '22 21:10

Jamund Ferguson