TypeScript - SetTimeOut bug on variable assign

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 ... ?

1 answer

  • answered 2020-10-23 12:20 Gunnar B.

    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);