0

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";
  }
}

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.