I have this start timer function
async startTimer() {
this.count = 30;
for (var i = 30; i >= 0; i--) {
await new Promise((f) => setTimeout(f, 1000));
this.count = i;
}
}
which gets started by calling this.startTimer()
but when i try to set this.count=0
to stop the timer it doesn't stop rather than when i run this.startTimer
again old one also run.
Any solution please. Thanks
CodePudding user response:
What happens after you set this.count = 0
?
startTimer
waits for promise, then it sets this.count = i
, then it does i--
, then it checks condition i >= 0
, so the loop simply continues. There is nothing that breaks the loop.
CodePudding user response:
Get rid of i
, use count
directly instead. Also introduce a isRunning
flag.
Following example still leverages to -1, since you can't cancel a promise.
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
count: number = 0;
isRunning: boolean = false;
async startTimer() {
if (!this.isRunning) {
this.isRunning = true;
for (this.count = 30; this.count >= 0 && this.isRunning; this.count--) {
await new Promise((f) => setTimeout(f, 1000));
}
this.isRunning = false;
}
}
stopTimer() {
this.isRunning = false;
}
}
Stackblitz: https://stackblitz.com/edit/angular-p4zg94?file=src/app/app.component.ts