Skip to content
Related Articles
Open in App
Not now

Related Articles

Node.js Immediate Timer Class

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 01 Jul, 2021
Improve Article
Save Article

The timer module is used for scheduling functions which will be called at some future period of time. It is a global API So, there is no need to import (require(“timers”)) to use it.

Immediate Class has an object (setImmediate()) which is created internally to scheduled actions, and (clearImmediate()) can be passed in order to cancel those scheduled actions.When an immediate is scheduled, By default, the event loop of Node.js will continue running until clearImmediate() is called. The setImmediate() Method returns immediate objects which are used to control this default behavior, exports both immediate.ref() and immediate.unref() functions.

The three immediate class objects are defined below: 

1. immediate.hasRef(): (Added in v11.0.0) This immediate object keeps the event loop active until the returned ‘True’ if returned ‘false’ breaks the event loop.



Return Value<boolean>: This immediate object keeps the event loop active if returned ‘True’.

2. immediate.ref(): (Added in v9.7.0) When the Immediate is active and (immediate.ref()) called then it requests that the Node.js event loop did not exit so long. Anyway, calling this Method multiple times does not have any effect. 



Return Value <Immediate>: It returns an immediate reference.

3. immediate.unref(): (Added in v9.7.0) When the Immediate is active it does not require the Node.js event loop to remain active. The callback of the Immediate object is invoked after the process gets exit if any other activity keeps the event loop running. Anyway, calling this Method also multiple times does not have any effect.



Return Value<Immediate>: It returns an immediate reference. 

Example: Filename: index.js  


// Node.js program to demonstrate the
// Immediate Class methods
// Setting Immediate by setImmediate Method
var Immediate = setImmediate(function alfa() {
// Printing Immediate.hasRef method
// Returns true
// Printing Immediate.ref before unref
// Returns timer reference
// Printing Immediate.unref method
// Returns Immediate reference and
// sets hasRef to false
// Printing Immediate.hasRef before unref
// Returns false
// Clears setInterval Immediate
// Prints after clearing Immediate

Run index.js file using the following command:

node index.js


1.> true

2.> Immediate {

  _idleNext: null, ……, [Symbol(triggerId)]: 1


3.> Immediate {

 _idleNext: null, ……, [Symbol(triggerId)]: 1


4.> false

5.> 2


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!