Trusted answers to developer questions

What is clearTimeout() in Node.js?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

In Node, a function called setTimeout allows us to schedule a function call with a delay of a specific number of milliseconds. The clearTimeout function is used to revoke the effect of the setTimeout function. In other words, when the clearTimeout function is called, the function call scheduled by setTimeout does not execute.

Both of these functions are found in the Timers module of Node.js.

More detail about the setTimeout function can be found here.

Parameters

clearTimeout(timerIdentifier);

In the above snippet of code, timerIdentifier is a Timeout object returned by the setTimeout function, as shown in the example below.

timeIdentifier is passed as a parameter to the clearTimeout function to revoke the respective scheduled function call.

Examples

console.log("Before the setTimeout call")
let timerID = setTimeout(() => {console.log("Hello, World!")}, 1000);
console.log("After the setTimeout call")
clearTimeout(timerID)

In the above snippet of code, we can see that the function call scheduled by the setTimeout function does not take place because it was cleared by the clearTimeout function.

function myFunction(platform){
console.log("Hi, Welcome to " + platform);
}
console.log("Before the setTimeout call")
let timerID = setTimeout(myFunction, 1000, "Educative");
console.log("After the setTimeout call")
clearTimeout(timerID)

In the above example, it is evident that the clearTimeout function call on line 9 unscheduled the function call, which was scheduled inside the setTimeout function on line 6.

RELATED TAGS

node.js

CONTRIBUTOR

Amaaz Ahmad
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?