0

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);
            };
        }
    }
}
BrianZhang
  • 87
  • 6
  • how can we test that ? did you read https://stackoverflow.com/help/minimal-reproducible-example ? – Mister Jojo Dec 26 '20 at 22:29
  • 2
    Does this answer your question? [setTimeout() inside JavaScript Class using "this"](https://stackoverflow.com/questions/5911211/settimeout-inside-javascript-class-using-this) or [How to access the correct `this` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Ivar Dec 26 '20 at 22:31
  • 1
    Also relevant [How does the “this” keyword work?](https://stackoverflow.com/q/3127429) | [How to access the correct `this` inside a callback?](https://stackoverflow.com/q/20279484) – VLAZ Dec 26 '20 at 22:33
  • @Ivar Thanks! I guess behaviour of this works differently inside callbacks. Used .bind(this) and it was fixed. – BrianZhang Dec 27 '20 at 00:28

0 Answers0