我開始制作一個簡單的游戲來測驗反應能力。當紅色矩形變成綠色時,玩家必須點擊圖形并顯示結果。問題是在單擊矩形后,計時器再次啟動。我為此使用了取消訂閱,但沒有結果。
示例:https : //stackblitz.com/edit/angular-ivy-w8uejd?file=src/app/app.component.ts
代碼:
HTML
<div (click)="onRegtangleClicked()" id="rectangle"></div>
<div >
<button (click)="onStartClicked()" >Start</button>
</div>
<p >You score is: {{time}} (lower is better)</p>
社會保障局
.rectangle {
position: relative;
height: 500px;
width: 100%;
background-color: rgb(255, 0, 0);
cursor: pointer;
}
.button{
margin-left: 40%;
margin-top: 2%;
position: relative;
}
.text{
font-size: large;
position: relative;
margin-left: 40%;
}
打字稿
import { Component, OnInit } from '@angular/core';
import { timer } from 'rxjs';
@Component({
selector: 'app-reflexgame',
templateUrl: './reflexgame.component.html',
styleUrls: ['./reflexgame.component.scss'],
})
export class ReflexgameComponent implements OnInit {
time: number = 0;
subscription: any;
constructor() {}
ngOnInit(): void {}
onStartClicked() {
let randomNumber:number = Math.random() * 5;
setInterval(() => {
document.getElementById('rectangle')!.style.backgroundColor = 'green';
this.observableTimer();
}, randomNumber * 1000);
}
onRegtangleClicked() {
this.subscription.unsubscribe();
}
observableTimer() {
this.subscription = timer(0, 1).subscribe((val) => {
this.time = val;
});
}
}
我不知道我錯在哪里?
uj5u.com熱心網友回復:
計時器一次又一次地重新啟動,因為在onStartClicked()您使用的方法中setInterval。您在時間間隔內定義的邏輯每x秒連續執行一次,直到您呼叫clearInterval(theIntervalToClear).
在您的情況下,您應該使用 asetTimeout僅在x秒過去后觸發一次邏輯。
干杯
uj5u.com熱心網友回復:
你的代碼中斷的原因是因為
- 您
unsubscribe()甚至在創建訂閱之前就打電話:要解決這個問題,您可以添加一個標志,以便了解訂閱是否處于活動狀態。 - 創建間隔時,最好清除該間隔。
兩個邏輯都對我有用,試一試
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/379938.html
