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