Node.js – Immediate Timer Class

Node.jsServer Side ProgrammingProgramming

The Immediate Timer class is used for scheduling the functions that we need to call at a certain period of time in future. These tasks can be scheduled by using the Immediate timer class and using the setImmediate() method. The Immediate class has an object for setImmediate() method and it passes the same object to clearImmediate() in case it wants to cancel the scheduled timer function.

Given below are the Immediate class ref objects −

1. immediate.ref()

This method is called if the immediate object is active for too long and did not exit.

Syntax

immediate.ref()

2. immediate.unref()

This object keeps the event loop ‘active’ until False is returned which will break the loop.

Syntax

immediate.Unref()

Example

Create a file with the name "immediate.js" and copy the following code snippet. After creating the file, use the command "node immediate.js" to run this code.

// Immediate Timer class Demo Example

// Setting Immediate by setImmediate Method
var Immediate = setImmediate(function immediate() {
   console.log("0.>",12);
});

// Printing Immediate.ref before unref
console.log("1. ",Immediate.ref());

// Printing Immediate.unref method
console.log("2. ",Immediate.unref());

// Clears setInterval Immediate
clearImmediate(Immediate);

// Prints after clearing Immediate
console.log("3. ","Thank you !");

Output

1. Immediate {
   _idleNext: null,
   _idlePrev: null,
   _onImmediate: [Function: immediate],
   _argv: undefined,
   _destroyed: false,
   [Symbol(refed)]: true,
   [Symbol(asyncId)]: 5,
   [Symbol(triggerId)]: 1 }
2. Immediate {
   _idleNext: null,
   _idlePrev: null,
   _onImmediate: [Function: immediate],
   _argv: undefined,
   _destroyed: false,
   [Symbol(refed)]: false,
   [Symbol(asyncId)]: 5,
   [Symbol(triggerId)]: 1 }
3. Thank you !
raja
Updated on 29-Oct-2021 08:59:59

Advertisements