1

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

mozpider
  • 366
  • 2
  • 12

1 Answers1

1

This seems to be issue with the context (this), because you have called this.startTime function directly by passing its reference. Since you have passed reference of this.startTime inside setInterval it is considered this as window object. And modify elapsedTime and put it inside window(this) object.

To fix this issue you can call this.startTimer method from the callback function of setInterval like below.

this.clock = setInterval(() => this.startTimer(), 1000);

OR change startTimer function to Arrow function to keep this intact.

startTimer = () => {
    const currentTime = new Date().getTime();
    // debugger;
    this.elapsedTime = currentTime - this.startTime; // place breakpoint here
}

Working Demo

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299