Explain clearTimeout() function in Node.js
Last Updated :
09 Jul, 2024
The clearTimeout()
function in Node.js is used to cancel a timeout that was previously established by calling setTimeout()
. When you set a timeout using setTimeout()
, it returns a timeout ID which you can later use to cancel the timeout if necessary. This can be particularly useful for stopping a scheduled function from executing after a specified delay, often in scenarios where the execution of the function becomes unnecessary or conditions change.
Syntax:
clearTimeout(timeoutID);
Parameter:
timeoutID
: The identifier of the timeout you want to cancel, which is returned by the setTimeout()
function.
Key Points of clearTimeout()
- Purpose: Cancel a scheduled function call.
- Usage: Prevents the function passed to
setTimeout()
from being executed. - Parameter: Takes a timeout ID (returned by
setTimeout()
) as its parameter. - Behaviour: No effect if the timeout has already been executed or if the ID does not correspond to a valid timeout.
Cancelling a Scheduled Function Call
Suppose you set a timeout to log a message after 5 seconds. You can cancel it before it executes.
const timeoutID = setTimeout(() => {
console.log('This will not be printed');
}, 5000);
// Cancel the timeout
clearTimeout(timeoutID);
In this example, the clearTimeout(timeoutID)
function call ensures that the console.log
statement inside setTimeout()
is never executed.
Conditionally Cancelling a Timeout
You can set a timeout to perform an action, such as fetching data, but cancel it if certain conditions are met.
let shouldCancel = true;
const timeoutID = setTimeout(() => {
console.log('Fetching data...');
}, 3000);
if (shouldCancel) {
clearTimeout(timeoutID);
console.log('Timeout cancelled');
}
Here, if shouldCancel
is true
, the timeout is cancelled, and the message "Fetching data..." is never logged.
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!
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
Best Practices
- Use clear naming conventions: When dealing with multiple timeouts, use descriptive variable names for timeout IDs to avoid confusion.
- Check if the timeout exists: Before calling
clearTimeout()
, ensure that the timeout ID is valid to avoid unnecessary function calls. - Clean up in asynchronous operations: Always clear timeouts in asynchronous operations or event listeners to prevent potential memory leaks or unwanted behavior.
Conclusion
The clearTimeout()
function in Node.js is a powerful tool for managing the execution of delayed functions. It provides control over timeouts, allowing you to cancel them based on dynamic conditions or events. Understanding how to use clearTimeout()
effectively helps in creating responsive and efficient applications.
Similar Reads
Explain V8 engine in Node.js
The V8 engine is one of the core components of Node.js, and understanding its role and how it works can significantly improve your understanding of how Node.js executes JavaScript code. In this article, we will discuss the V8 engineâs importance and its working in the context of Node.js.What is a V8
7 min read
What is a callback function in Node?
In the context of NodeJS, a callback function is a function that is passed as an argument to another function and is executed after the completion of a specific task or operation. Callbacks are fundamental to the asynchronous nature of NodeJS, allowing for non-blocking operations and enabling effici
2 min read
p5.js | duration() Function
The duration() function is an inbuilt function in p5.js library. This function is used to return the duration of a sound file in seconds which is loaded the audio on the web. Basically when you trigger this function then it will return the time in the second dot microsecond format of that audio's pl
1 min read
Event Demultiplexer in Node.js
Node.js is designed to handle multiple tasks efficiently using asynchronous, non-blocking I/O operations. But how does it manage multiple operations without slowing down or blocking execution? The answer lies in the Event Demultiplexer.The Event Demultiplexer is a key component of Node.js's event-dr
3 min read
How to Delay a Function Call in JavaScript ?
Delaying a JavaScript function call involves executing a function after a certain amount of time has passed. This is commonly used in scenarios where you want to postpone the execution of a function, such as in animations, event handling, or asynchronous operations. Below are the methods to delay a
2 min read
Underscore.js _.delay() Function
Underscore.js _.delay() function executes the mentioned function in its argument after waiting for the specified milliseconds. It is mostly used when we want to perform some task but after a certain amount of time. In this case, we can define this function, and then it will be executed after the wai
4 min read
Underscore.js _.after() Function
Underscore.js is a JavaScript library that provides a lot of useful functions that help in the programming in a big way like the map, filter, invoke, etc even without using any built-in objects. The _.after() function is an inbuilt function in Underscore.js library of JavaScript which is used to cre
2 min read
Underscore.js _.debounce() Function
Underscore.js _.debounce() Function in Underscore.js is used to create a debounced function that is used to delay the execution of the given function until after the given wait time in milliseconds has passed since the last time this function was called. The debounced function has a cancel method th
2 min read
File handling in Node.js
The most important functionalities provided by programming languages are Reading and Writing files from computers. Node.js provides the functionality to read and write files from the computer. Reading and Writing the file in Node.js is done by using one of the coolest Node.js modules called fs modul
4 min read
What is Self-Executing Function?
A self-executing function is a function in JavaScript that doesn't need to be called for its execution it executes itself as soon as it is created in the JavaScript file. This function does not have a name and is also called an anonymous function. This function is initialized inside a set of round b
2 min read