Node.js – Timeout-ref() & Timeout-unref() method

Node.jsServer Side ProgrammingProgramming

The Timeout object is internally created and is returned from the setTimeout() and setInterval() methods. You can use this object and pass it to either clearTimeout() or clearInterval() if you want to cancel the scheduled actions.

Following are the timeout class ref objects that can be used to control the default behaviour −

1. timeout.ref()

This method is called if the timeout object's event loop does not exist. The actual use of this method is only after the timeout.unref() is called, and you need to reference the timeout object again.

Syntax

timeout.ref()

2. timeout.unref()

This method will tell the timeout object that the Node.js event loop does not need to be active anymore. If there is no other activity or process running, the process may exit before the Timeout object's callback is invoked.

Syntax

timeout.unref()

Example

Create a file with the name "timeout.js" and copy the following code. After creating the file, use the command "node timeout.js" to run this code as shown in the example below

// Timeout class Demo Example

// Setting the Timeout using setTimeout() Method
var Timeout = setTimeout(function fun() {
   console.log("1. Setting Timeout for 100ms", 100);
});

// Checking if the timeout.hasRef() object
console.log("2. ", Timeout.hasRef();

// Printing the Timeout ref
console.log("3. ", Timeout.ref());

// Unreferencing and referencing again
console.log("4. ", Timeout.unref());

// Checking if the reference is removed ?
console.log("5. ", Timeout.hasRef());

Timeout.ref()

// Refreshing the timer
console.log("6. ", Timeout.hasRef());

// Clears setInterval Timeout
clearTimeout(Timeout);

console.log("7. Timeout is cleared !");

Output

It will produce the following output −

2. true
3. Timeout {
   _called: false,
   _idleTimeout: 1,
   _idlePrev: [TimersList],
   _idleNext: [TimersList],
   _idleStart: 358,
   _onTimeout: [Function: fun],
   _timerArgs: undefined,
   _repeat: null,
   _destroyed: false,
   [Symbol(unrefed)]: false,
   [Symbol(asyncId)]: 5,
   [Symbol(triggerId)]: 1 }
4. Timeout {
   _called: false,
   _idleTimeout: 1,
   _idlePrev: null,
   _idleNext: null,
   _idleStart: 358,
   _onTimeout: [Function: fun],
   _timerArgs: undefined,
   _repeat: null,
   _destroyed: false,
   _handle: [Timer],
   [Symbol(unrefed)]: false,
   [Symbol(asyncId)]: 5,
   [Symbol(triggerId)]: 1 }
5. false
6. true
7. Timeout is cleared !
raja
Published on 24-Nov-2021 07:13:16
Advertisements