Explanation
I am writing a program to measure reaction time, and I have this class that I'm trying to create that measures the time taken to react. After calling the startDelayTimer() which is when the "start" button in my program would be pressed, it creates a random delay from 1 to 4 seconds, and then the screen turns green and you have to press the spacebar when it turns green. The problem is, the first console.log() in calculateDelayTime() outputs undefined as the value of this.timeElapsed. In startDelayTimer(), this.timeElapsed is still 0. I'm not sure why it is undefined. Any advice?
Code
class ReactionTimer {
constructor() {
this.timeTotal = Math.floor(Math.random() * 301) * 10;
this.timeElapsed = 0;
}
startDelayTimer() {
this.timer = setInterval(this.calculateDelayTime, 10);
}
calculateDelayTime() {
console.log(this.timeElapsed);
this.timeElapsed += 10;
if (this.timeElapsed >= this.timeTotal) {
clearInterval(this.timer);
document.querySelector(".rectangle").style.backgroundColor =
"green";
this.timeElapsed = 0;
this.timer = setInterval(() => {
this.timeElapsed += 1;
}, 1);
document.onkeydown = () => {
clearInterval(this.timer);
document.onkeydown = null;
console.log(this.timeElapsed);
};
}
}
}