UPDATE:Plunkr鏈接:https://plnkr.co/edit/NkLUPWH3yNHrPjvYoYdE?p=infoangular2計時器進入無限
我所試圖做的事: 在我的模板,我填充圖標分三路從三個表的一個又一個的每個在第二。爲此,我在組件中有三個圖標列表。在特定級別和特定級別中還有其他一些改變圖標顏色的條件。 Start()被調用開始按鈕單擊並調用處理圖標填充邏輯的iterator()。當列表中的圖標結束或用戶單擊停止按鈕時,定時器應該停止。
在iterator()函數中我有一個定時器,每兩秒調用一次相同的函數。計時器應該在所有數組項目都被覆蓋但不能正常工作時停止。
我的HTML
<div class="col col1" align="center">
<div class="ionicon1">
<ion-icon name="{{current_symbol_for_list1}}" [ngClass]="{'makeBlue': makeBlue1, 'makeRed': makeRed1}"></ion-icon>
</div>
</div>
<div class="col col2" align="center">
<div class="ionicon2">
<ion-icon name="{{current_symbol_for_list2}}" [ngClass]="{'makeBlue': makeBlue2, 'makeRed': makeRed2}"></ion-icon>
</div>
</div>
<div class="col col3" align="center">
<div class="ionicon3">
<ion-icon name="{{current_symbol_for_list3}}" [ngClass]="{'makeBlue': makeBlue3, 'makeRed': makeRed3}"></ion-icon>
</div>
</div>
</div>
我的組件
level= 1;
round=1
ionicon_class_list=[
'alarm', 'android', 'apple', 'radio-button-on',
'basket', 'beer', 'radio-button-on', 'boat',
'book', 'bowtie']
current_symbol_for_list=''
current_symbol_for_list1=''
current_symbol_for_list2=''
current_symbol_for_list3=''
myCounter: any;
i=0;
length = this.ionicon_class_list.length;
start(){
this.iterator(this.i)
}
iterator(){
if(this.level==1 || this.level==3 || this.level==5 || this.level==6){
/* Handle at Level 1 for all the 3 rounds*/
if(this.level==1 && this.round==1 && this.current_symbol_for_list2=='apple'){
this.makeBlue2=true;
}
else if(this.level==1 && this.round==1 && this.current_symbol_for_list2=='radio-button-on'){
this.makeBlue2=false
}
...
/* Middle list will have the 'dot' symbol */
this.current_symbol_for_list2=this.ionicon_class_list[this.i]
this.current_symbol_for_list1=this.ionicon_class_fake_list1[this.i]
this.current_symbol_for_list3=this.ionicon_class_fake_list2[this.i]
if(++this.i<this.length) {
console.log("i "+ this.i)
/* Implement timer that runs the same iterator function after 1 second*/
this.timer = Observable.timer(1000,2000);
this.myCounter = this.timer.subscribe(
t => {
this.iterator();
});
}
else if(this.i>=this.length){
this.myCounter.unsubscribe();
this.current_symbol_for_list2=null
this.current_symbol_for_list1=null
this.current_symbol_for_list3=null
this.i=0
}
}
不知怎的,這段時間不會停止,並進入無限。我究竟做錯了什麼?
能否請您解釋正是你想達到什麼樣的?我敢肯定有一個簡單的解決方案,但只有代碼在這種情況下並不真正幫助:) – Maxime
我確實用Plunkr更新了我的anwser。讓我知道你對它的看法;) – Maxime