Steven Lu Steven Lu - 6 months ago 17
Node.js Question

Node.js: Will node always wait for setTimeout() to complete before exiting?


node -e "setTimeout(function() {console.log('abc'); }, 2000);"

This will actually wait for the timeout to fire before the program exits.

I am basically wondering if this means that node is intended to wait for all timeouts to complete before quitting.

Here is my situation. My client has a node.js server he's gonna run from Windows with a Shortcut icon. If the node app encounters an exceptional condition, it will typically instantly exit, not leaving enough time to see in the console what the error was, and this is bad.

My approach is to wrap the entire program with a try catch, so now it looks like this:
try { (function () { ... })(); } catch (e) { console.log("EXCEPTION CAUGHT:", e); }
, but of course this will also cause the program to immediately exit.

So at this point I want to leave about 10 seconds for the user to take a peek or screenshot of the exception before it quits.

I figure I should just use blocking
through the npm module, but I discovered in testing that setting a timeout also seems to work. (i.e. why bother with a module if something builtin works?) I guess the significance of this isn't big, but I'm just curious about whether it is specified somewhere that node will actually wait for all timeouts to complete before quitting, so that I can feel safe doing this.


In general, node will wait for all timeouts to fire before quitting normally. Calling process.exit() will exit before the timeouts.

The details are part of libuv, but the documentation makes a vague comment about it:

you can call ref() to explicitly request the timer hold the program open

Putting all of the facts together, setTimeout by default is designed to hold the event loop open (so if that's the only thing pending, the program will wait). You can programmatically disable or re-enable the behavior.