The Timers
module is a global module that is part of the standard library. Timers
provide utilities and functions to schedule the execution of blocks of code at a set time.
The Timer
module provides a Timeout
class, which is created internally when the setTimeout()
or setInterval()
methods return. Timeout
can be passed to clearTimeout()
or clearInterval()
to cancel the scheduled events.
The event loop of Node.js continues to run as long as Timer
is active. The Timeout
class provides the Timeout.ref()
and Timeout.unref()
methods to control the default behavior of the event loop.
When the Timout.ref()
method is called, it requests the event loop to continue running as long as Timeout
is active. If the method is called multiple times, it has no effect.
timeout.ref()
The Timeout.ref()
method returns a reference to timeout
of type Timeout
.
If we use the Timeout.unref()
function here, it will request that the event loop become inactive. In this case, there is no other event keeping the event loop running, so it will terminate before the callback to setTimeout()
is invoked.
const Timeout = setTimeout(function alfa() {console.log("Timeout for 1000ms");}, 1000);Timeout.unref();console.log("callback not invoked")
However, if we call Timeout.ref()
right after the unref()
call, we request that the event loop remains active. In this case, the event loop will wait for the callback for setTimeout()
to be invoked.
const Timeout = setTimeout(function alfa() {console.log("Timeout for 1000ms");}, 1000);Timeout.unref();console.log("call back will be invoked")Timeout.ref();
Free Resources