【发布时间】:2022-02-11 20:17:22
【问题描述】:
我正在 Angular 中构建一个基本计时器。为此,我有两个按钮,其中一个启动计时器,另一个停止它。我正在以 1000 毫秒的延迟实现 setInterval。但是当我按下停止按钮时,计时器停止但 timeoutId 没有被清除。我想防止用户在第一个计时器没有完成时不启动另一个计时器。我使用 - if (this.timeoutId) return; - 但是当我停止它时,我无法再次启动它。 问题是如何防止用户在计时器启动时启动新计时器。当我停止它时如何重新启动它。
//game-control-component.ts
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-game-control',
templateUrl: './game-control.component.html',
styleUrls: ['./game-control.component.css'],
})
export class GameControlComponent implements OnInit {
@Output() onIncrement: EventEmitter<number> = new EventEmitter();
timer: number = 0;
timeoutId!: ReturnType<typeof setTimeout>;
constructor() {
console.log(this.timeoutId);
}
increment() {
this.timer++;
}
startTimer() {
if (this.timeoutId) return;
this.timeoutId = setInterval(() => {
this.increment();
this.onIncrement.emit(this.timer);
}, 1000);
}
stopTimer() {
clearInterval(this.timeoutId);
console.log(this.timeoutId);
}
ngOnInit(): void {
console.log(this.timeoutId);
}
}
//游戏控制组件-html
<div class="row mt-5">
<div class="col-12">
<div class="button-group d-flex justify-content-evenly">
<button (click)="startTimer()" class="btn btn-primary">Start</button>
<button (click)="stopTimer()" class="btn btn-danger">Stop</button>
</div>
<h1 class="mt-5" style="text-align: center">{{ timer }}</h1>
</div>
【问题讨论】:
-
this.timeoutId = null呢? -
您是否允许或可以使用 RxJs,如果是,我可以展示另一种使用 RxJs 创建简单计时器的替代解决方案。
-
this.timeoutId = null;我得到错误。我无法将 Timeout 类型分配为 null。我认为它来自打字稿。 “类型 'null' 不能分配给类型 'Timeout'。我还不知道 RxJs。
标签: javascript angular setinterval