Getting setInterval to cooperate with anything inside of a class apparently is impossible in this language. Here’s what I have so far:
class Timer {
duration;
isRunning;
constructor (durationInSeconds) {
this.duration = durationInSeconds;
this.isRunning = false;
}
startTimer() {
this.isRunning = true;
this.interval = setInterval(updateTimer, 1000);
}
updateTimer() {
console.log(this.duration);
console.log(this.isRunning);
let minutes = parseInt(this.duration / 60, 10);
let seconds = parseInt(this.duration % 60, 10);
seconds = seconds < 10 ? "0" + seconds : seconds;
let timerHTML = document.getElementById("timer");
timerHTML.innerHTML = '<strong>' + minutes + ":" + seconds + '</strong>';
if (--this.duration < 0) {
console.log('Time is up');
this.isRunning = false;
}
}
}
Without switching to Java which I would much prefer, what is the way to get this to work?
I tried writing a timer class in javascript, a huge mistake apparently
I was expecting it to work, a huger mistaker apparentlier
>Solution :
Your reference to updateTimer is incorrect. Try:
this.interval = setInterval(this.updateTimer.bind(this), 1000);
It’s an instance method, so you must use this to refer to the function. The bind method ensures your method also has the right this when it gets called.
As pointed out in one of the comments, you can also use a lambda:
this.interval = setInterval(() => this.updateTimer(), 1000);
This a special function declaration syntax that specifically uses the this of where it was defined when called, so you don’t need to bind it.