Categories
JavaScript Answers

How to check if a setInterval timer is running and stop it with JavaScript?

Spread the love

Sometimes, we want to check if a setInterval timer is running and stop it with JavaScript.

In this article, we’ll look at how to check if a setInterval timer is running and stop it with JavaScript.

How to check if a setInterval timer is running and stop it with JavaScript?

To check if a setInterval timer is running and stop it with JavaScript, we can call clearIntveral with the timer variable.

For instance, we write:

<button>
  stop
</button>

to add a button.

Then we write:

const interval = setInterval(() => {
  console.log('hello')
}, 2000);

const button = document.querySelector('button')
button.onclick = () => {
  clearInterval(interval)
}

to call setInterval with a callback that runs every 2 seconds.

Then we select the button with querySelector.

And we set button.onclick to a function that calls clearInterval to clear the timer.

Conclusion

To check if a setInterval timer is running and stop it with JavaScript, we can call clearIntveral with the timer variable.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *