A Node program does not stay alive without a reason to do so. A process will keep running for as long as there are callbacks still waiting to be processed. Once those are cleared, the Node process has nothing left to do, and it will exit.

For example, the following silly code fragment will keep a Node process running forever:

let intervalId = setInterval(() => {}, 1000);

Even though the set callback function does nothing useful or interesting, it continues to be called. This is the correct behavior, as an interval should keep running until clearInterval is used to stop it.

The unref method allows the developer to assert the following instructions: when this timer is the only event source remaining for the event loop to process, go ahead and terminate the process. Let's test this functionality to our previous silly example, which will result in the process terminating rather than running forever:

let intervalId = setInterval(() => {}, 1000); 

intervalId.unref();

Now, let's add an external event source, a timer. Once that external source gets cleaned up (in about 100 milliseconds), the process will terminate. We sendinformation to the console to log what is happening:

setTimeout(() => { console.log("now stop"); }, 100); 

let intervalId = setInterval(() => { console.log("running") }, 1); 

intervalId.unref();

You may return a timer to its normal behavior with ref , which will undo an unref method:

let intervalId = setInterval(() => {}, 1000); 

intervalId.unref(); 

intervalId.ref();

results matching ""

    No results matching ""