0

Currently I am trying to build an 'in-game' clock so to speak for an application that I am building. What I wanted to have was to create a class of Time and add a setInterval() to increase the time of the seconds attribute to test


class Time {
    constructor() {
        this.seconds = 0;
        this.countTime = setInterval(this.increaseTime, 1000)
    }

    increaseTime() {
        this.time++
        console.log(this.seconds)
    }

}

let time = new Time();

What I expected was that my function would increase the this.seconds property with the setInterval function I passed through. Instead in the console it kept printing out NaN every second. Does anyone have a clue what's going on?

pythonNovice
  • 1,130
  • 1
  • 14
  • 36

1 Answers1

1

It is because setInterval is running the callback in the global context and this is not pointing to the class. you can bind this to this variable in the lexical scope or use arrow functions.

  class Time {
    constructor() {
        this.seconds = 0;
        this.countTime = setInterval(this.increaseTime.bind(this), 1000)
    }

    increaseTime() {
        this.seconds++
        console.log(this.seconds)
    }

}

let time = new Time();
Ali
  • 468
  • 1
  • 8
  • 19