0

I am still learning javascript. I am trying to write a class to act as a timer. However, it appears that the callback function that I pass to setInterval never gets called. Here is my code:

class GameTimer {
    construtor() {
        this.interval = undefined;
        this.time = 0;              // seconds
    }

    start(seconds) {        
        this.time = seconds;
        this.interval = setInterval(this.tick, 1000);
    }

    tick() {
        this.time--;
    }

    getTime() {
        return this.time;
    }

    stop() {
        clearInterval(this.interval);
    }

    reset() {
        this.time = 0;
    }
}

// Test
var gameTimer = new GameTimer();

var currentTime = 10;
gameTimer.start(currentTime );

while (gameTimer.getTime() > 0) {
   if (gameTimer.getTime() != currentTime) {
      console.log(gameTimer.getTime());
      currentTime = gameTimer.getTime();
   }
}

When I run the code it gets caught in an infinite loop. After putting in some logging, I could see that tick() never gets called. There may be a better way of building a timer than this and I am open to any suggestions, however what I am hoping to figure out is what I am doing wrong here that is causing tick() to never be called. Thanks for any help.

user2970381
  • 93
  • 3
  • 11
  • 1
    when you pass `this.tick` as a callback, the function loses its relationship to your object. You can pass `this.tick.bind(this)` to get over that problem. – Pointy Mar 26 '20 at 23:01
  • another common method is to add `this.tick = this.tick.bind(this)` to the constructor (before the setInterval) – Jaromanda X Mar 26 '20 at 23:03

0 Answers0