What is clearTimeout() in Node.js?

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.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved