JS中的守护程序
我正在编写一个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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以利用
timeout ute> timeout.unref()
:因此
const timeouthandle = settimeout(()=> showwarning(),5000); timeouthandle.unref();
这将阻止
settimeout
保持该过程活动。You can utilize
timeout.unref()
:So
const timeoutHandle = setTimeout(() => showWarning(), 5000); timeoutHandle.unref();
This will prevent the
setTimeout
to keep the process active.