Node.js – Timers Module – Cancelling Timers


A timer can only be cancelled after it is being scheduled. The Immediate class has an object for setImmediate() method and passes the same object to clearImmediate(), in case it wants to cancel the scheduled timer function.

Scheduling Timers

This type of timers schedules the task to take place after a certain instant of time.

  • setImmediate()

  • setInterval()

  • setTimeout()

Cancelling Timers

This type of timers cancels the scheduled tasks which is set to take place.

  • ClearImmediate()

  • clearInterval()

  • clearTimeout()

1. clearImmediate() method

This method clears the Immediate timer object that is created by the setImmediate() method.

Syntax

clearImmediate( timer )

Example

filename - clearImmediate.js

// clearImmediate() Example

var timer = setImmediate(function A() {
   console.log("Timer set");
});

clearImmediate(timer);
console.log("Timer cancelled");

Output

Timer cancelled

2. clearInterval() method

This method clears the Immediate timer object that is created by the setInterval() method.

Syntax

clearInterval( timer )

Example

filename - clearInterval.js

// clearInterval() Example

var si = setInterval(function A() {
   return console.log("Setting Intervals for 500 ms !");
}, 500);

// Cleared the interval from 1000 ms
setTimeout(function() {
   clearInterval(si);
}, 1000);

Output

Setting Intervals for 500 ms !

3. clearTimeout() method

This method clears the Immediate timer object that is created by the setTimeout() method.

Syntax

clearTimeout( timerObject )

Example

filename - clearTimeout.js

// clearTimeout() Example

var timer = setTimeout(function A() {
   return console.log("Hello TutorialsPoint!");
}, 500);

// timer2 will be executed
var timer2 = setTimeout(function B() {
   return console.log("Welcome to TutorialsPoint!");
}, 500);

clearTimeout(timer);

Output

Welcome to TutorialsPoint!

Updated on: 24-Nov-2021

202 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements