Open In App

Explain clearTimeout() function in Node.js

Last Updated : 16 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In node.js, there exists a timer module that is used to schedule timers and execute some kind of functionality in some future time period.

JavaScript setTimeout() Method: It is used to schedule functionality to be executed after provided milliseconds, below is a simple example of setTimeout() method.

Example: The setTimeout inside the script tag is registering a function to be executed after 3000 milliseconds and inside the function, there is only an alert.

Javascript




function alertAfter3Seconds() {
    console.log("Hi, 3 Second completed!");
}
setTimeout(alertAfter3Seconds, 3000);


Output:

Hi, 3 Second completed!

JavaScript clearTimeout() Method: This method comes under the category of canceling timers and is used to cancel the timeout object created by setTimeout. The setTimeout() method also returns a unique timer id which is passed to clearTimeout to prevent the execution of the functionality registered by setTimeout. 

Example: Here we have stored the timer id returned by setTimeout, and later we are passing it to the clearTimeout method which immediately aborts the timer.

Javascript




function alertAfter3Seconds() {
    alert("Hi, 3 Second completed!");
}
  
const timerId = setTimeout(alertAfter3Seconds, 3000);
  
clearTimeout(timerId);
console.log("Timer has been Canceled");


Output: Here we will not be able to see that alert registered to be executed after 3000 milliseconds because clearTimeout canceled that timer object before execution.

Timer has been Canceled

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads