Different ways to cancel active timers in Node.js

How to cancel active timers in Node.js :

If you have activated one timer, you may need to cancel it sometime.

Node.js provides 3 different ways to schedule a timer. Following are these methods :

  1. setImmediate

  2. setInterval

  3. setTimeout

setImmediate :

This method is used to schedule one execution immediately. It returns one Immediate object. It has one variant defined in the util package called util.promisify that returns promises.

setInterval :

setInterval is used for repeated execution. It takes one callback function and one delay in milliseconds and repeats the callback function. It returns one Timeout object.

setTimeout :

setTimeout also takes one callback function and one delay time in milliseconds. But it will execute that code only for one time. It returns one Timeout object. Similar to setImmediate, we can use util.promisify to get one promise object.

Canceling the timers :

We can cancel any timer object that is created. Note that we can’t cancel the promise variants of setImmediate and setTimeout. Each of these methods returns one object. We can call the cancel methods on these objects.

1. Cancel immediate timer :

The below method is used to cancel one immediate timer i.e. a timer object that was created by the setImmediate method :

clearImmediate(obj)

Here, obj is an Immediate object that was returned by the setImmediate method.

2. Cancel interval timer :

To cancel one interval timer or a timer created by setInterval, the below method is used :

clearInterval(obj)

Here, obj is a Timeout object returned by the setInterval method.

3. Cancel timeout timer :

To cancel one timeout timer or a timer created by setTimeout, the below method is used :

clearTimeout(obj)

Here, obj is a Timeout object returned by the setTimeout method.