3

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.

0

2 Answers 2

8

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();
7
  • Great answer! And I was being pessimistic if this was possible at all... :) Thank you!!!
    – vitaly-t
    Oct 25, 2015 at 3:00
  • @vitaly-t - You are very welcome. I though it was a very nice convenience when they added it. Oct 25, 2015 at 3:03
  • Just so, clearTimeout part shouldn't be in the answer, it is only unref that's usable for the kind of example I provided ;)
    – vitaly-t
    Oct 25, 2015 at 3:22
  • @vitaly-t - You could use clearTimeout if you wanted to maintain a set of references to active timers, and then have some sort of cleanup function that was called as part of your application exit process. Should have added that in my first sentence in the answer. Oct 25, 2015 at 7:05
  • it's just that the point of my question was how to avoid making any explicit calls in the end of the application, and still be able to exit, which is what unref does nicely, but clearTimeout doesn't help here :)
    – vitaly-t
    Oct 25, 2015 at 7:17
0

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).

3
  • I've just added an example to illustrate the point of the question.
    – vitaly-t
    Oct 25, 2015 at 2:42
  • I've extended my answer.
    – Matt Way
    Oct 25, 2015 at 2:55
  • Thank you, but barry-johnson gave the right answer.
    – vitaly-t
    Oct 25, 2015 at 3:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.