我想通过播放和开始按钮启动和停止循环,但它不起作用。当我按下测试按钮时,我有一个无限循环。
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 :(得分:0)
您必须将this.isPlayed
设置为false
(或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);
}
答案 1 :(得分:0)
我认为虽然循环不会起作用。您可以尝试使用setInterval和clearInterval
public timer;
play() {
this.timer= setInterval(function () {
console.log("test") // this is inside your loop
}, 100);
};
stop() {
clearInterval( this.timer);
};