I have a class called Timer:
class Timer {
#tick() {
console.error('Error usage of interface Timer explicitly deleted');
}
startTimer() {
console.error('Error usage of interface Timer explicitly deleted');
}
}
And I have a class called CyclingTimer which derives from Timer:
class CyclingTimer extends Timer {
#maximumTime
#timeBetweenTicks
#currentTime
#onTick
constructor(maximumTime, timeBetweenTicks) {
super();
this.#maximumTime = maximumTime;
this.#timeBetweenTicks = timeBetweenTicks;
this.#currentTime = 1;
}
#validateBoundaries() {
if(this.#currentTime > this.#maximumTime) this.#currentTime = 1;
else if(this.#currentTime < 1) this.#currentTime = this.#maximumTime;
}
#tick() {
//I console.log(this) here to debug and it printed the Window object as this. I don't know why
this.#currentTime++; //Error Occures In This Line
this.#validateBoundaries();
this.#onTick();
}
startTimer() {
//When I console.log(this) here it prints CyclingTimer as expected
setInterval(this.#tick, this.#timeBetweenTicks);
}
setOnTickFunction(callbackFunction) {
this.#onTick = callbackFunction;
}
}
I have no clue why this happens and these are the only things I have. When I searched about the error I found nothing.
I finally solved the issue. The problem was when using setInterval() 'tick()' lost its 'this' to solve this issue I bind 'tick()' to my object than pass binded function to setInterval()