Reputation: 25920
Is it possible in NodeJS to implement a version of setTimeout
that wouldn't block the process from exiting once the last line of code has finished?
i.e. the kind of conditional setTimeout
that would only trigger the callback function provided the process is still running.
Practical example:
When implementing a library that initializes itself by setting up some timeouts, you would want that once the app has finished, you don't need to make an explicit call into that library to clear all the timeouts, and let the app shut down regardless.
Upvotes: 4
Views: 4476
Reputation: 3224
You can use clearTimeout
if you wanted to maintain references to all your outstanding timers and then clear them as part of your application exit process, but it is much easier in node to use unref()
Node doc on unref
. The effect is that any unref
ed timer will not prevent Node from exiting.
For example:
var to = setTimeout(myFunction,delay);
to.unref();
Works with setInterval as well
setInterval(myFunction,delay).unref();
Upvotes: 9
Reputation: 33179
If you look at the docs for setTimeout, you will notice that it returns a timeoutObject that can be used to cancel the timeout via clearTimeout(obj)
.
So what you could do is keep track of all the timeouts you create by storing their id objects. Then you are able end all the timeouts whenever you want.
If you simply want to exit the process, ignoring everything else, you can just use process.exit()
(passing an argument if you want to return a non zero error code).
Upvotes: 0