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.