How to enable/disable button in setInterval function


#1

Hi,

I am not sure if this is really an Ionic question, but here we go.

What I expect: in the record function, the button is disabled after clicking on it, and enabled after the condition is triggered in an inner setInterval function.

Problem: value assigned to buttonDisabled in setInterval function does not enable the button again.

in html, I have a button

<button ion-button icon-only (click)="record()" [disabled]="buttonDisabled"><ion-icon name="recording"></ion-icon></button>

in ts, I have

export class runPage {
  buttonDisabled: boolean = false;
.....

  record(){
    audioObject.startRecord();
    this.buttonDisabled = true;

    let id = setInterval(function () {
      //do something;
      if (// a condition) {
        clearInterval(id);
        audioObject.stop();
        audioObject.release();
        this.buttonDisabled = false;  // <== this assignment does not enable the button in the view.
      }
    }, 1000);
  }
}

How to Change the Background color in Ionic after 10 seconds
#2

Seems like a classic scoping issue to me. Use a lambda function instead of a normal function and I think it should work.

let id = setInterval( () => {
      //do something;
      if (// a condition) {
        clearInterval(id);
        audioObject.stop();
        audioObject.release();
        this.buttonDisabled = false;  // <== this assignment does not enable the button in the view.
      }
    }, 1000);

#3

man, it really is! Thanks so much, I will google what lambda brought in for this scoping issue.