简体   繁体   中英

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?

ie 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 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();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM