我有三个功能。在按钮点击事件上调用第一个函数,即Start()
。 start()
在startFilling()
设置的特定秒数后调用另一个函数counter1
(此计数器递减,我在模板上显示)。 startFilling()
应在另一个checkCorrectness()
设置的特定秒数后调用另一个函数counter2
(此计数器也会递减,我会在模板上显示)。
我的HTML:
<!-- Show counter -->
<div align="center" style="margin-bottom:1cm;" *ngIf="counter1">
<h5>Countdown {{counter1}}</h5>
</div>
<div align="center" style="margin-bottom:1cm;" *ngIf="counter2">
<h5>Countdown {{counter2}}</h5>
</div>
我的代码如下:
counter1=5;
counter2=null;
myCounter1: any;
myCounter2: any;
start(){
/* Set the counter to fire the startFilling() function after specific seconds */
let timer = Observable.timer(1000,1000);
this.myCounter1 = timer.subscribe(t=> this.startFilling(t));
}
startFilling(counter){
this.counter1=this.counter1-1;
if(this.counter1==0){
this.counter1=null;
alert("Filling finished")
this.myCounter1.unsubscribe();
this.counter2=11;
}
if(this.level===1 || this.level===2 || this.level===3){
let timer = Observable.timer(this.counter2, 1000);
this.myCounter2 = timer.subscribe(t=> this.checkCorrectness(t));
}
if(this.level===4 || this.level===5 || this.level===6 || this.level===7){
let timer = Observable.timer(this.counter2,1000);
this.myCounter2 = timer.subscribe(t=> this.checkCorrectness(t));
}
}
checkCorrectness(counter){
this.counter2=this.counter2-1;
if(this.counter2==0){
this.counter2=null;
alert("Check correctness")
this.myCounter2.unsubscribe();
}
}
这里的问题是:我希望屏幕上只能显示一个计数器,在我的情况下,它们都显示出来。此外,他们在某种程度上重叠并进入负面。
我该如何解决这个问题?
答案 0 :(得分:1)
我会抽象计时器创建方法以及counter2持续时间。
<uses-feature android:name="android.hardware.telephony" android:required="false" />
答案 1 :(得分:0)
我修改了我的代码,如下所示:
startFilling(counter){
this.counter1=this.counter1-1;
if(this.counter1==0){
this.counter1=null;
alert("Filling finished")
this.myCounter1.unsubscribe();
if(this.level===1 || this.level===2 || this.level===3){
this.counter2=11;
let timer2 = Observable.timer(1000, 1000);
this.myCounter2 = timer2.subscribe(t=> this.checkCorrectness(t));
}
if(this.level===4 || this.level===5 || this.level===6 || this.level===7){
this.counter2=14;
let timer2 = Observable.timer(1000, 1000);
this.myCounter2 = timer2.subscribe(t=> this.checkCorrectness(t));
}
}
}
checkCorrectness(counter){
this.counter2=this.counter2-1;
if(this.counter2==0){
this.counter2=null;
alert("Check correctness finished")
this.myCounter2.unsubscribe();
}
}
如果有更好的方法,请提出建议。