Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I just want a simple timer class in javascript, why is setInterval such a pain?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading