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
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?
CodePudding user response:
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.isRunning = false; // Its started so stop it');
clearInterval(intervalId);
}
}