JavaScript clearInterval()

JavaScript clearInterval()

As a web developer, I have used JavaScript to create animations and timers on my web pages. However, sometimes I need to stop a timer or an animation that is running. This is where the clearInterval() method comes in handy.

What is clearInterval()?

clearInterval() is a JavaScript method that stops a timer that was set up using the setInterval() method. The setInterval() method is used to run a function or a piece of code repeatedly at a set interval.

How to use clearInterval()

To use clearInterval(), you need to first set up a timer using the setInterval() method. Here is an example:


var myTimer = setInterval(myFunction, 1000);
function myFunction() {
  console.log("Hello World!");
}

In this example, a function called myFunction() is executed every 1000 milliseconds (1 second). The setInterval() method returns an ID which can be used to stop the timer using clearInterval().

Here is an example of how to use clearInterval() to stop the timer:


clearInterval(myTimer);

This code will stop the timer that was set up using the setInterval() method and assigned to the variable myTimer.

Multiple Timers

If you have multiple timers running, you can use multiple variables to store the IDs returned by the setInterval() method. Then, you can use the clearInterval() method on each of these variables to stop the corresponding timer.


var timer1 = setInterval(function() {
  console.log("Timer 1");
}, 1000);

var timer2 = setInterval(function() {
  console.log("Timer 2");
}, 2000);

clearInterval(timer1);

In this example, two timers are set up using the setInterval() method and assigned to the variables timer1 and timer2. The first timer logs "Timer 1" every 1000 milliseconds (1 second) and the second timer logs "Timer 2" every 2000 milliseconds (2 seconds). The clearInterval() method is used to stop the first timer (timer1).

Conclusion

The clearInterval() method is a useful tool for stopping timers that are running on a web page. By using multiple variables to store the IDs returned by the setInterval() method, you can easily stop individual timers. Remember to use clearInterval() to stop your timers and prevent your web page from becoming sluggish due to unnecessary background processes.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe