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.

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 *