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

Making a clock autorefresh using setInterval

i wanted to build a clock and my only problem here is that setInterval basically does not work. Am I missing something

const timer = document.getElementById("container")
let currentTime = new Date()

let hours = currentTime.getHours()
let minutes = currentTime.getMinutes()
let seconds = currentTime.getSeconds()



function time () {

        let hoursIf = hours.toString().length==1 ? "0"+hours : hours
        let minutesIf = minutes.toString().length==1 ? "0"+ minutes : minutes
        let secondsIf = seconds.toString().length==1 ? "0" +seconds : seconds

        timer.textContent = `${hoursIf}:${minutesIf}:${secondsIf}`

}
time()
let run = setInterval(time, 1000)

>Solution :

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

It works, trust me. The problem is the assigment in:

let hours = currentTime.getHours()
let minutes = currentTime.getMinutes()
let seconds = currentTime.getSeconds()

You’re assigning time once at the start, and don’t check for updated values later. If you’d put that in your time function it would work properly.
Something like this:

function time () {
        let currentTime = new Date()

        let hours = currentTime.getHours()
        let minutes = currentTime.getMinutes()
        let seconds = currentTime.getSeconds()

        let hoursIf = hours.toString().length==1 ? "0"+hours : hours
        let minutesIf = minutes.toString().length==1 ? "0"+ minutes : minutes
        let secondsIf = seconds.toString().length==1 ? "0" +seconds : seconds

        timer.textContent = `${hoursIf}:${minutesIf}:${secondsIf}`

}
time()
let run = setInterval(time, 1000)
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