Categories
JavaScript Answers

How to stop a setTimeout loop with JavaScript?

Spread the love

Sometimes, we want to stop a setTimeout loop with JavaScript.

In this article, we’ll look at how to stop a setTimeout loop with JavaScript.

How to stop a setTimeout loop with JavaScript?

To stop a setTimeout loop with JavaScript, we can call the clearTimeout function.

For instance, we write

let timeOutVar;
const myFunc = (terminator = false) => {
  if (terminator) {
    clearTimeout(timeOutVar);
  } else {
    timeOutVar = setTimeout(myFunc, 1000);
  }
};
myFunc(true);
myFunc(false);

to define the myFunc function.

In it, we call clearTimeout with timeOutVar if terminator is true to stop the timer.

Otherwise, we call setTimeout with myFunc and assign it to timeOutVar.

Then we call myFunc with true to start the timer.

And we call myFunc with false to stop it.

Conclusion

To stop a setTimeout loop with JavaScript, we can call the clearTimeout 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.