2017-06-06 17 views
0

我想用播放和開始按鈕啓動和停止循環,但它不起作用。當我按下測試按鈕時,我有一個無限循環。播放/停止按鈕來控制循環

import { Component } from '@angular/core'; 
import { NavController } from 'ionic-angular'; 
import { Vibration } from '@ionic-native/vibration'; 

@Component({ 
    selector: 'page-home', 
    templateUrl: 'home.html' 
}) 

export class HomePage { 

    isPlayed: boolean = false; 

    constructor(public navCtrl: NavController, private vibration: Vibration) { 

    } 

    play(){ 
    this.isPlayed = true; 
    this.test(); 
    console.log(this.isPlayed); 
    } 

    stop(){ 
    this.isPlayed = false; 
    this.test(); 
    console.log(this.isPlayed); 
    } 

    test(){ 
    while (this.isPlayed == true) { 
     console.log("test") 
    } 
} 
} 

和HTML:

<ion-header> 
    <ion-navbar> 
    <ion-title> 
     Pulse 
    </ion-title> 
    </ion-navbar> 
</ion-header> 

<ion-content padding> 
    <button ion-button (click)="play()"> 
    Play 
    </button> 
    <button ion-button (click)="stop()"> 
    Stop 
    </button> 
    <button ion-button (click)="test()"> 
    Test 
    </button> 
    {{counter}} 
</ion-content> 
+0

*「我有一個無限循環」 * - 好'而(this.isPlayed ==真)'要麼永遠不會運行或一直運行下去,這樣看來不足爲奇。 – jonrsharpe

+0

@jonrsharpe我認爲OP的顯而易見的迴應是「但stop()'函數沒有這樣做嗎?」 – Santi

+0

是的,但我認爲當我點擊停止按鈕時,它會更新布爾值。我該怎麼做? – user2182652

回答

0

你必須設置this.isPlayedfalse(或falsy值)爲while循環停止。但是您不能運行stop(),因爲console.log正在不斷執行。

也許你可以用setInterval測試:

private interval; 

    test(){ 
     if (this.interval) { 
      return; 
     } 

     this.interval = setInterval(() => { 
      if (this.isPlayed) { 
       console.log('playing'); 
      } else { 
       console.log('stopped'); 
      } 
     }, 1000); 
    } 
+0

是的,我這樣做,但它不起作用。循環開始時,我無法按任何按鈕。 – user2182652

+0

它做了太多工作('console.log'不斷髮生)。也許你可以用'setInterval'來測試它。我會更新我的答案。 –

+0

'play(){ this.isPlayed = true; while(this.isPlayed == true)setInterval(console.log(「test」),2000); (){ this.isPlayed = false; } } console.log(this.isPlayed); } }' 我做到了,但它不起作用,我不能使用停止按鈕。循環保持循環。 – user2182652

0

我覺得while循環不會工作。你可以嘗試在使用setInterval和clearInterval嘗試

public timer; 

    play() { 
     this.timer= setInterval(function() { 
      console.log("test") // this is inside your loop 
     }, 100); 
    }; 

    stop() { 
     clearInterval(this.timer); 
    };