typescript 使用Angular 中的承诺停止计时器

jjhzyzn0  于 2022-11-26  发布在  TypeScript
关注(0)|答案(2)|浏览(148)

我有这个启动定时器功能

async startTimer() {
    this.count = 30;
    for (var i = 30; i >= 0; i--) {
      await new Promise((f) => setTimeout(f, 1000));
      this.count = i;
    }
  }

它通过调用this.startTimer()启动,但当我尝试设置this.count=0以停止计时器时,它不会停止,而当我再次运行this.startTimer时,旧的计时器也会运行。
有什么办法吗?谢谢

elcex8rz

elcex8rz1#

设置this.count = 0之后会发生什么?startTimer等待承诺,然后它设置this.count = i,然后它执行i--,然后它检查条件i >= 0,所以循环只是继续,没有任何东西会中断循环。

tmb3ates

tmb3ates2#

去掉i,直接使用count。同时引入一个isRunning标志。
下面的例子仍然利用-1,因为你不能取消一个承诺。

@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;
  }
}

堆栈 lightning 战:https://stackblitz.com/edit/angular-p4zg94?file=src/app/app.component.ts

相关问题