JS中的守护程序

发布于 2025-02-14 00:48:20 字数 566 浏览 9 评论 0原文

我正在编写一个node.js库,该库需要设置才能运行。如果在5秒内未运行设置功能,我已经使用SettiMeout显示了警告。

但是,这使程序在退出之前等待5秒钟,即使所有其他代码都已完成。

我想显示一条警告消息,如果尚未调用设置功能,并且该程序在5秒后仍在运行。有没有办法使用香草JS来做到这一点?

const done = new Event(); // Event is a simple class I made for a one-time event multicast

function setup() {
  done.emit();
}

const timeoutHandle = setTimeout(() => showWarning(), 5000);
done.subscribe(() => {
  clearTimeout(timeoutHandle);
});

console.log("The program should end here");

// The program keeps going for 5 seconds even after the last statement

I am writing a node.js library that requires setup in order to run. I have used setTimeout to show a warning if the setup function isn't run within 5 seconds.

However, this makes the program wait for 5 seconds before exiting, even if all the other code is finished.

I want to show a warning message iff the setup function hasn't been called and the program is still running after 5 seconds. Is there a way to do this with vanilla JS?

const done = new Event(); // Event is a simple class I made for a one-time event multicast

function setup() {
  done.emit();
}

const timeoutHandle = setTimeout(() => showWarning(), 5000);
done.subscribe(() => {
  clearTimeout(timeoutHandle);
});

console.log("The program should end here");

// The program keeps going for 5 seconds even after the last statement

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

肩上的翅膀 2025-02-21 00:48:21

但是,这使程序在退出之前等待5秒钟,即使所有其他代码都完成。

您可以利用 timeout ute> timeout.unref()

调用时,活动超时对象将不需要node.js事件循环保持活动状态。如果没有其他活动保持事件循环运行,则该过程可能会在调用超时对象的回调之前退出。调用timeout.unref()多次没有效果。

因此const timeouthandle = settimeout(()=> showwarning(),5000); timeouthandle.unref();

这将阻止settimeout保持该过程活动。

However, this makes the program wait for 5 seconds before exiting, even if all the other code is finished.

You can utilize timeout.unref():

When called, the active Timeout object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before the Timeout object's callback is invoked. Calling timeout.unref() multiple times will have no effect.

So const timeoutHandle = setTimeout(() => showWarning(), 5000); timeoutHandle.unref();

This will prevent the setTimeout to keep the process active.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文