| by Arround The Web | No comments

How to Cancel Interval, Immediate, and Timeout Objects in Node.js?

Node.js offers the “Timers” module for scheduling the desired task to be performed after a specific time interval. It is useful to schedule the functions that can be called later at a given time. This module performs this main functionality with the help of its several built-in scheduling “setInterval()”, “setImmediate()”, and the “setTimeout()” methods. Once the scheduled timer functions are set with the help of specified methods, the user can cancel them by using their returned objects according to the requirements.

This post will elaborate on all possible methods to cancel the interval, immediate, and timeout objects in Node.js.

How to Cancel Interval, Immediate, and Timeout Objects in Node.js?

To cancel the scheduled “Timers” objects that have been set with the help of the “setInterval()”, “setImmediate()”, and the “setTimeout()”, use the following methods:

Let’s start with the “clearInterval()” method to cancel the “Interval” object.

Method 1: Cancel “Interval” Object Using “clearInterval()”

The “clearInterval()” is the predefined method of the “Timers” module that cancels the scheduled “Interval” time object set with the help of the “setInterval()” method. This method takes the “Interval” object as its argument and stops the infinite execution of specific code blocks.

The “setInterval()” method is used for the execution of a code block repeatedly after the specified time delay.

Syntax

The generalized syntax of the “clearInterval()” method is as follows:

clearInterval(intervalID)

 

The above syntax supports only one parameter “intervalID” which is the returned id of the “setInterval()” method.

Return Value: The “clearInterval()” method returns “NONE” as it only halts the “Interval” object.

Here is the practical implementation of the above-defined method.

Example: Applying the “clearInterval()” Method to Cancel the Infinite Loop Execution

This example utilizes the “setInterval()” method to execute the given function repeatedly and then applies the “clearInterval()” method to cancel its infinite execution:

let count=0;
const setTimeID = setInterval(myFunc, 1000);
function myFunc() {
 console.log("Linuxhint!");
count++;
if (count === 4) {
 console.log('\nGiven Interval has been stopped after 4th executions\n');
 clearInterval(setTimeID);
 }
}

 

In the above lines of code:

  • Firstly, the “let” keyword declares the “count” variable with a numeric value.
  • Next, the “setTimeID” object uses the “setInterval()” method to execute the specified function repeatedly after the given delay.
  • In this function, the “console.log()” method prints the specified statement in the console.
  • After that, increment the “count” variable using the “count++” statement.
  • Now, the “if” statement defines a code block in which the “console.log()” method will display the given statement, and the “clearInterval()” with the returned id of the “setInterval()” method will stop the execution of the above-defined function based on the “if” condition.

Output

Execute the “.js” file using the following command:

node app.js

 

It can be observed that the particular function is executed for a limited number of times:

Method 2: Cancel “Immediate” Object Using “clearImmediate()”

The “clearImmediate()” is a built-in method of the “Timers” module that stops the immediate execution of the specified code block that has been set using the “setImmediate()” method. This method takes the returned ID of the “setInterval” method and cancels the “Immediate” timer object execution.

The “setImmediate()” method is used to execute the code immediately without any delay in the next iteration of the event loop.

Syntax

The basic syntax of the “clearImmediate()” method is written below:

clearImmediate(intervalID)

 

Similar to the “clearInterval()” method, the “clearImmediate()” method only supports the “intervalID” that is returned by the “setImmediate()” method.

Return Value: The “clearImmediate()” method returns “NONE” as it only cancels the “Immediate” timer object.

After getting the basics of the “clearImmediate()” method, let’s move on to its practical implementation to understand how to stop the “Immediate” timer object using it.

Example: Applying the “clearImmediate()” Method to Cancel the “Immediate” Timer Object

This example applies the “setImmediate()” method to execute the specified function after all the runnable code has been executed, and the “clearImmediate()” method to cancel its execution:

console.log("Before the setImmediate call")
function myFunc(arg){
 console.log("Welcome to " + arg);
}
let timerID = setImmediate(myFunc, "Linuxhint");
console.log("After the setImmediate call")
for(let i=0; i<5; i++){
 console.log("Iteration: "+i);
}
clearImmediate(timerID)

 

In the above code snippet:

  • Firstly, the “console.log()” method displays the quoted text statement in the console.
  • Next, define a function named “myFunc()”.
  • In its function definition, the “console.log()” method prints the given statement along with the passed argument.
  • Now, the “timerID” applies the “setImmediate()” method that takes the specified function and the given argument as its first and the second parameters respectively.
  • The next “console.log()” method prints another statement.
  • The “for” loop displays the specified statement using the “console.log()” method based on the specified condition.
  • Lastly, the “clearImmediate()” method takes the “timerID” object as the returned id of the “setImmediate()” method to cancel its execution.

Output

Run the “app.js” file:

node app.js

 

The following output does not show the execution of the “setImmediate()” method right after the completion of all other statements because it has been canceled via the “clearImmediate()” method:

Method 3: Cancel “Timeout” Object Using “clearTimeout()”

The “clearTimeout()” is a method of the “Timers” module that cancels the “Timeout” object returned by the “setTimeout()” method. This method stops the execution of the specified code before its execution.

The predefined “setTimeout()” method provides a convenient way to execute the desired code after a specified time interval only once. Its main objective is to add a delay in the specific part of code execution.

Syntax

The generalized syntax of the “clearTimeout()” method is stated here:

clearTimeout(intervalID)

 

Like the above two methods, the “clearTimeout()” method also takes only the “intervalID” returned by the “setTimeout()” method.

Return Value: The “clearTimeout()” method returns “NONE” as it only cancels the “Timeout” timer object.

Example: Applying the “clearTimeout()” Method to Cancel the “Timeout” Timer Object

This example omits the “delay” parameter of “setTimeout()” to achieve the zero delay:

const myTimeout = setTimeout(myFunc, 2000);
function myFunc() {
 console.log("Welcome to Linuxhint!")
}
clearTimeout(myTimeout);
console.log(" Scheduling Timers has been Canceled");

 

In the above lines of code:

  • The “myTimeout” object applies the “setTimeout()” method to execute the specified function after the specified “delay” given as its parameter.
  • In the function definition, the “console.log()” method is utilized to show the specified text statement in the console.
  • The “clearTimeout()” method takes the returned ID of the “setTimeout()” method and cancels its execution.
  • The “console.log()” method displays the quoted statement.

Output

Initiate the “app.js” file of your project using the “node” keyword:

node app.js

 

The output shows that the defined function execution has been canceled because of the “clearTimeout()” method:

That’s all about canceling the “Interval”, “Immediate”, and “Timeout” timer objects.

Conclusion

To cancel the “Interval” object use “clearInterval”, for the “Immediate” object utilize the “clearImmediate()”, and for the “Timeout()” use the “clearTimeout()” method. All of these methods work on the returned “intervalID” of the methods that set the timer objects based on their names and functionalities. This post has elaborated on all possible methods to cancel the interval, immediate, and timeout objects in Node.js.

Share Button

Source: linuxhint.com

Leave a Reply