The clearInterval()
method in JavaScript is used to stop an interval that was previously created using the setInterval()
method. This method takes a single argument, which is the interval ID that was returned by the setInterval()
method when the interval was created.
Here is an example of how the clearInterval()
method works:
// create an interval that logs a message every second
const intervalId = setInterval(() => {
console.log('Hello, world!');
}, 1000);
// stop the interval after 5 seconds
setTimeout(() => {
clearInterval(intervalId);
}, 5000);
In the code example above, we first use the setInterval()
method to create an interval that logs the message 'Hello, world!'
to the console every second. The setInterval()
method returns an interval ID, which we store in the intervalId
variable.
We then use the setTimeout()
method to stop the interval after 5 seconds. The setTimeout()
method calls the clearInterval()
method, passing the intervalId
variable as an argument. This stops the interval that was previously created with the setInterval()
method.
As a result of calling the clearInterval()
method, the interval that was created with the setInterval()
method will be stopped. The 'Hello, world!'
message will be logged to the console for 5 seconds, and then the interval will be stopped and the message will no longer be logged.
Leave a Reply