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.
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.
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.
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.
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.
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?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With