The clearTimeout()
method in JavaScript is used to stop a timeout that was previously created using the setTimeout()
method. This method takes a single argument, which is the timeout ID that was returned by the setTimeout()
method when the timeout was created.
Here is an example of how the clearTimeout()
method works:
// create a timeout that logs a message after 5 seconds
const timeoutId = setTimeout(() => {
console.log('Hello, world!');
}, 5000);
// stop the timeout after 3 seconds
setTimeout(() => {
clearTimeout(timeoutId);
}, 3000);
In the code example above, we first use the setTimeout()
method to create a timeout that logs the message 'Hello, world!'
to the console after 5 seconds. The setTimeout()
method returns a timeout ID, which we store in the timeoutId
variable.
We then use the setTimeout()
method again to stop the timeout after 3 seconds. The setTimeout()
method calls the clearTimeout()
method, passing the timeoutId
variable as an argument. This stops the timeout that was previously created with the setTimeout()
method.
As a result of calling the clearTimeout()
method, the timeout that was created with the setTimeout()
method will be stopped. The 'Hello, world!'
message will not be logged to the console, because the timeout was stopped before the specified delay of 5 seconds elapsed.
Leave a Reply