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.

By John Au-Yeung

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

One reply on “How to pause setInterval() functions with JavaScript?”

Leave a Reply

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