播放/停止按钮控制循环



我想开始并停止使用播放和启动按钮停止循环,但它不起作用。按测试按钮时,我有一个无限的循环。

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>

您必须将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);
  }

我认为循环时无法工作。您可以尝试使用setInterval和clear Interval

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

最新更新