0

I tried to code a JavaScript timer that would increment a value each second and update the innerHTML of a DOM element to show the time. The first tick works, but after that timerEngine.time goes undefined and incrementing it in tick() produces NaN. Why does the variable go undefined though?

Here's the code:

const timerEngine = {
    time: 0,
    timerID: -1,

    tick() {
        this.time++;
        if (this.time % 60 < 10)
            document.getElementById("timer").innerHTML = `${Math.floor(this.time / 60)}:0${this.time % 60}`;
        else
            document.getElementById("timer").innerHTML = `${Math.floor(this.time / 60)}:${this.time % 60}`;
    },

    start() {
        if (this.timerID === -1)
            this.timerID = setInterval(this.tick, 1000);
    },

    stop() {
        if (this.timerID !== -1) {
            clearInterval(this.timerID);
            this.timerID = -1;
        }
    },

    reset() {
        this.stop();
        this.time = -1;
        this.tick();
    }
}

The timer is started in a function:

someFunction() {
    // some code
    timerEngine.reset();
    timerEngine.start();
}

0 Answers0