Exploring Angular and TypeScript for an Ionic project, I am working on a simple functionality. A button click changes the text displayed, followed by another change after a short delay.
I'm facing confusion around why "this.text" does not work as expected, depending on how the timeout function is implemented.
The following code snippet shows where the issue arises:
export class HomePage {
constructor() { }
text = "Default";
onChangeText() {
this.text = "Changed!";
setTimeout(
this.onBackToDefault
, 2000);
}
onBackToDefault() {
this.text = "Default";
}
}
However, the problem is resolved with the revised code below:
export class HomePage {
constructor() { }
text = "Default";
onChangeText() {
this.text = "Changed!";
setTimeout(() => {
this.onBackToDefault();
}
, 2000);
}
onBackToDefault() {
this.text = "Default";
}
}