退出AlertController并停止函数调用

时间:2018-11-11 12:02:35

标签: javascript ionic-framework ionic3

我有一个function,它显示警报控制器和一个按钮,单击该按钮可以更新Firestore数据库上的字段。 15秒后,警报消失,另一个功能被触发。

pickupIsRequested(){
    this.pickupRequest.pickupStatus.subscribe(value => {
        console.log(value);

        if(value == true){
            let alert = this.alertCtrl.create({
                title: 'You have a Pickup Request!',
                message: '<span>Princess who is 3 minutes away requests a ride</span><hr/> You have 15 seconds to accept the request!',
                buttons: [
                    {
                        text: 'Accept Ride',
                        handler: () => {
                            this.driver.updateDriverInRide(true, this.driverId);
                        }
                    }
                ]
            });
            alert.present();

            setTimeout(() => {
                alert.dismiss();
                this.driver.updateDriverPickupRequest(false, this.driverId);
            }, 15000);
        }
    }); 
}

单击警报控制器按钮后,如何停止function方法上的setTimeout调用?现在,如果我单击按钮,this.driver.updateDriverPickupRequest仍会触发。

1 个答案:

答案 0 :(得分:2)

您可以使用clearTimeout()取消功能

pickupIsRequested(){
   // First you need to create your timeout
   let myTimeout = setTimeout(() => {
       alert.dismiss();
       this.driver.updateDriverPickupRequest(false, this.driverId);
      }, 15000);

  this.pickupRequest.pickupStatus.subscribe(value => {
              console.log(value);

              if(value == true)
              {
                   let alert = this.alertCtrl.create({
                    title: 'You have a Pickup Request!',
                    message: '<span>Princess who is 3 minutes away requests a ride</span><hr/> You have 15 seconds to accept the request!',
                    buttons: [
                      {
                        text: 'Accept Ride',
                        handler: () => {
                          this.driver.updateDriverInRide(true, this.driverId);
                          // Cancel it here
                          clearTimeout(myTimeout);
                        }
                      }
                    ]
                  });
                  alert.present();
              }
    }); 

}