Categories
JavaScript Answers

How to pause setInterval() functions with JavaScript?

Spread the love

Sometimes, we want to pause setInterval() functions with JavaScript.

In this article, we’ll look at how to pause setInterval() functions with JavaScript.

How to pause setInterval() functions with JavaScript?

To pause setInterval() functions with JavaScript, we call the clearInterval function.

For instance, we write

let doThis = null;

const y = () => {
  //...
};

doThis = setInterval(y, 1000);

const yStart = () => {
  doThis = setInterval(y, 1000);
};

const yStop = () => {
  clearInterval(doThis);
};

to define the yStart function.

In it, we call setInterval with y and 1000 to call y every second.

We assign the returned timer ID to the doThis variable.

Then we define the yStop function that calls clearInterval with doThis to stop the timer.

Conclusion

To pause setInterval() functions with JavaScript, we call the clearInterval function.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.