简体   繁体   English

非阻塞setTimeout

[英]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? 在NodeJS中是否有可能实现setTimeout的版本,该版本不会在最后一行代码完成后阻止进程退出?

ie the kind of conditional setTimeout that would only trigger the callback function provided the process is still running. 也就是说,条件setTimeout的类型仅在进程仍在运行时才触发回调函数。

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 . 如果要维护对所有未完成计时器的引用,然后在应用程序退出过程中将其清除,则可以使用clearTimeout ,但是在node中在unref()上使用unref() Node doc要容易unref The effect is that any unref ed timer will not prevent Node from exiting. 结果是任何未unref计时器都不会阻止Node退出。

For example: 例如:

var to = setTimeout(myFunction,delay);
to.unref();

Works with setInterval as well 也可以与setInterval一起使用

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) . 如果看一下setTimeout的文档,您会注意到它返回了一个timeoutObject,该对象可用于通过clearTimeout(obj)取消超时。

So what you could do is keep track of all the timeouts you create by storing their id objects. 因此,您可以做的是通过存储其id对象来跟踪创建的所有超时。 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). 如果您只是想退出该进程,而忽略其他所有内容,则可以使用process.exit() (如果要返回非零错误代码,则传递一个参数)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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