0

I am working with Ionic and Angular wich means that I am working with TypeScript language.

I have a boolean that is supposed to become false if there is a click on an element and if that same boolean is true. After the boolean becomes false a setTimeOut() function is runned so that after 5000ms the boolean becomes true again.

The problem I am facing is when the setTimeOut() is runned. The boolean becomes true. However when I click on the element again (after 5000ms) the boolean is false ...

Where is the code:

resendSMS() {
  console.log('allowResendSMS: ', this.allowResendSMS);

  if (this.allowResendSMS) {
    this.allowResendSMS = false;
    console.log('SMS HAS BEEN RESENDED');
    console.log('allowResendSMS: ', this.allowResendSMS);

    setTimeout(function () {

      this.allowResendSMS = true;
      console.log('END OF TIMEOUT');
      console.log('allowResendSMS: ', this.allowResendSMS)

    }, 5000);
  } 
}

Where is the output:

(First Click on Element)
allowResendSMS:  true
SMS HAS BEEN RESENDED
allowResendSMS:  false
END OF TIMEOUT
allowResendSMS:  true

(Second Click on Element)
allowResendSMS:  false
END OF TIMEOUT
allowResendSMS:  true

Can someone give a clue of why the allowresendSMS is false on the second click and even why it's beeing runned the setTimeOut() when this boolean haves a false value ... ?

Grinnex.
  • 869
  • 2
  • 12
  • 23
  • 1
    Use arrow function to refer `this` to the scope of the class: `setTimeout(() => {...}, 5000);`. – ruth Oct 23 '20 at 12:22

1 Answers1

1

I think in your code the this in this.allowResendSMS = true scopes to the function (the context of this changes), not the surrounding class.

Replace

setTimeout(function () {
  this.allowResendSMS = true;
  console.log('END OF TIMEOUT');
  console.log('allowResendSMS: ', this.allowResendSMS)
}, 5000);

with

setTimeout(() => {
  this.allowResendSMS = true;
  console.log('END OF TIMEOUT');
  console.log('allowResendSMS: ', this.allowResendSMS)
}, 5000);
Gunnar B.
  • 2,879
  • 2
  • 11
  • 17