javascript - ionicangular 2: string does not updated after settimeout - Stack Overflow

admin2025-04-20  0

I'm trying to update a string (of a class\tag) with settimeout (or any other callback), with no success, It's working perfectly with a button (when the user is clicking the button to update), but it doesn't work with JS settimeout. can you tell me what am I missing here?

Here is a sample of the code I have:

export class Page1 {
  constructor() {
this.greet = "Hi, ";
setTimeout(function(){
  this.greet = "Hello, ";
  alert("Done");
 }, 3000);
  }
}

as you can see in this simple code, I can see the alert "Done" after 3 seconds, but the greeting is not updated, should I refresh it somehow?

Thanks for helping!

Eran.

I'm trying to update a string (of a class\tag) with settimeout (or any other callback), with no success, It's working perfectly with a button (when the user is clicking the button to update), but it doesn't work with JS settimeout. can you tell me what am I missing here?

Here is a sample of the code I have:

export class Page1 {
  constructor() {
this.greet = "Hi, ";
setTimeout(function(){
  this.greet = "Hello, ";
  alert("Done");
 }, 3000);
  }
}

as you can see in this simple code, I can see the alert "Done" after 3 seconds, but the greeting is not updated, should I refresh it somehow?

Thanks for helping!

Eran.

Share Improve this question asked Jun 6, 2016 at 5:38 Eran LeviEran Levi 9092 gold badges14 silver badges31 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

In your way this inside setTimeout callback isn't instance of Page1 class. You need to use arrow function to retain context:

setTimeout(() => { // <=== 
  this.greet = "Hello, ";
  alert("Done");
}, 3000);

See this link for more details https://developer.mozilla/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Lexical_this

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745114741a285796.html

最新回复(0)