Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular can start button cannot stop the interval

I am using Angular and I have this code:

App.component.ts

started: boolean = false;

…

startStop() {
    if (!this.started) {
      setInterval(()=> { this.test() }, 1000); // not started so start the interval   
      this.started = true;
    } else if (this.started) {
      this.started = false;  // Its started so stop it');
      clearInterval();
    }
  }


test() {
  // do stuff only via interval if started
}

Then I have a button that turns it on and off

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

app.component.html

<button (click)=“startStop()”>Start / Stop</button>

The interval turns on but not off eventhough the variable "started" is changed to false.

How can I fix this issue?

>Solution :

This is not how clearInterval works. What if you have several intervals ? Which one will it stop ?

setInterval returns an id that you should pass to clearInterval

startStop() {
    let intervalId
    if (!this.started) {
      intervalId = setInterval(()=> { this.test() }, 1000); // not started so start the interval   
      this.started = true;
    } else if (this.started) {
      this.started = false;  // Its started so stop it');
      clearInterval(intervalId);
    }
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading