I have a variable elapsedTime, initialized in the constructor as 0
. I am watching it in Chrome devtools debugger as this.elapsedTime
. It is initialized correctly. I also put a breakpoint in a method that will use this variable.
Angular goes on, does its thing, loads different components and the watched variable becomes NaN
. I suppose the context of this
is getting lost.
How to do this correctly?
Here is the snippet for the code -
import { Component, OnInit } from "@angular/core";
@Component({
selector: "app-game-control",
templateUrl: "./game-control.component.html",
styleUrls: ["./game-control.component.css"]
})
export class GameControlComponent implements OnInit {
startTime: number;
elapsedTime: number;
clock: any;
constructor() {
this.startTime = new Date().getTime();
this.elapsedTime = 0; // Correctly displays as initialized to 0 in watch variables
this.clock = setInterval(this.startTimer, 1000);
}
ngOnInit() {}
startTimer() {
const currentTime = new Date().getTime();
// debugger;
this.elapsedTime = currentTime - this.startTime; // place breakpoint here
}
}