3

This is a typescript class. I am trying to access the starttime & count in setInterval function. I have set the values before,why do we get undefined and NaN in it? and how do I solve this issue?

startTimer() {
 this.startTime = new Date();
 this.count = 100;
 console.log("STARTTIME: " + this.startTime); //RESULT: Mon Dec 17..etc
 console.log("COUNT: " + this.count); //RESULT: 100
    this.timer = setInterval(function () {
      console.log("STARTTIME: " + this.startTime); //Undefined
      this.count += 1;
      console.log("COUNT: " + this.count); //NaN
     }, 1000);
 }
Java Gamer
  • 567
  • 3
  • 9
  • 24
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – ConnorsFan Dec 17 '18 at 00:42

1 Answers1

12

Try using fat arrow instead of function

(from the docs)

this has traditionally been a pain point in JavaScript. As a wise man once said "I hate JavaScript as it tends to lose the meaning of this all too easily". Fat arrows fix it by capturing the meaning of this from the surrounding context.

Therefore use it like this:

setInterval(() => {  // <-----
  console.log("STARTTIME: " + this.startTime); 
  this.count += 1;
  console.log("COUNT: " + this.count); 
}, 1000);

Stackblitz

Flyii
  • 1,105
  • 1
  • 12
  • 21