MrAmericanMike
MrAmericanMike

Reputation: 149

Confuse with TS and Angular using setTimeoutFunction

I'm trying something very simple with Angular and TS for an Ionic practice. I have a simple button that when clicked changes a text, and then after a few seconds I want that text changed again.

I'm confuse as to why "this.text" wont work depending on how the timeout function is used.

This doesn't work. (this.text is undefined)

export class HomePage {
  constructor() { }

  text = "Default";

  onChangeText() {
    this.text = "Changed!";
    setTimeout(
      this.onBackToDefault
      , 2000);
  }

  onBackToDefault() {
    this.text = "Default";
  }
}

While this works

export class HomePage {
  constructor() { }

  text = "Default";

  onChangeText() {
    this.text = "Changed!";
    setTimeout(() => {
      this.onBackToDefault();
    }
      , 2000);
  }

  onBackToDefault() {
    this.text = "Default";
  }
}

Upvotes: 0

Views: 31

Answers (2)

AlleXyS
AlleXyS

Reputation: 2598

setTimeout(
  this.onBackToDefault
, 2000);

In this example, the setTimeout method know only elements declared inside it. So, all elements using this. will be undefined.

you need to use setTimeout using pharanteses to can use external parameters:

setTimeout(() => {    
// do stuff    
}, 2000);

Upvotes: 1

Kurt Hamilton
Kurt Hamilton

Reputation: 13515

It's because this when used inside a function refers to the function itself. When used in an arrow function, it refers to the outer scope.

In the first example, you are passing in the whole function, whereas you are using an arrow function in the second example.

The first example could also be written in longhand like this:

onChangeText() {
  this.text = "Changed!";
  setTimeout(function () {
    this.onBackToDefault();
//       <------ 'this' is scoped to the anonymous function
  }, 2000);
}

Upvotes: 2

Related Questions