SetInterval ref and unref in NodeJS

A NodeJS process is alive as along as it has some events and callbacks that are to be processed. So if we have a simple setInterval function in a file, it means the node processor has always some events to be processed periodically.

Simply adding this line will make the node run this script file forever!

There are mostly cases when execution flow has logically stopped, the setIntervals that have been created no longer make sense and its sensible for the node to terminate the process.

The ref and unref does exactly that operation over the setInterval id objects.

unref – so in the above example id.unref() means we inform nodejs that it can terminate the process if the id referenced interval call is the only event loop hogging to be processed.

ref – ref does the opposite of unref. according to some condition if id referenced interval call is meaningful and is going to affect the process outcome even if all other logics have completed execution we can do a id.ref() (if we have called id.unref() before on some condition) to make it actively hogging event processing loop for nodejs. So nodejs wont quit if that id referenced interval call is still active.

Leave a Reply