Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-blocking setTimeout

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.

like image 227
vitaly-t Avatar asked Oct 28 '25 04:10

vitaly-t


1 Answers

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();
like image 112
barry-johnson Avatar answered Oct 29 '25 19:10

barry-johnson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!