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.
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 unrefed 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();
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