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

Timer in a local scope variable in javascript

The timer must be initialized and the seconds have to be incremented each second. Can someone help me? I am not sure what is going on.

function timer(){
    let seconds = "00";
    let minutes = "00";
    let hours = "00";
    let fulltime = `${hours}:${minutes}:${seconds}`;

    const incrementSeconds = () => {
        secondsAsNumber = parseInt(seconds) + 1;
        seconds = secondsAsNumber.toString();
    }
    
    const displayTime = () => {
        console.log(fulltime);
    }
    
    setInterval(() => {
        incrementSeconds();
        displayTime();
    }, 1000);
}

timer();

It logs:

00:00:00
00:00:00
00:00:00
00:00:00
00:00:00
00:00:00
00:00:00

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

>Solution :

Update your fulltime variable after incrementing seconds:

function timer(){
    let seconds = "00";
    let minutes = "00";
    let hours = "00";
    let fulltime = `${hours}:${minutes}:${seconds}`;

    const incrementSeconds = () => {
        secondsAsNumber = parseInt(seconds) + 1;
        seconds = secondsAsNumber.toString();
        // Update fulltime variable
        fulltime = `${hours}:${minutes}:${seconds < 10 ? "0" + seconds : seconds}`;
    }
    
    const displayTime = () => {
        console.log(fulltime);
    }
    
    setInterval(() => {
        incrementSeconds();
        displayTime();
    }, 1000);
}

timer();

Then it should output:

00:00:01
00:00:02
00:00:03
00:00:04
00:00:05

... and so on ...
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