skip to Main Content

I’m trying to make a html and JavaScript clock, but the setInterval function in JS is not updating the text in html every second.

const time = new Date();
const time_text = document.getElementById("time");
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();

function displayTime() {
  time_text.innerHTML = String(hours + ":" + minutes + ":" + seconds);
}

setInterval(displayTime, 1000);
<div id="time"><div>

2

Answers


  1. Chosen as BEST ANSWER

    var time = new Date();
    var timeText = document.getElementById("time");
    var hours = time.getHours();
    var minutes = time.getMinutes();
    var seconds = time.getSeconds();
    
    function displayTime() {
        time = new Date()
        hours = time.getHours();
        minutes = time.getMinutes();
        seconds = time.getSeconds();
        timeText.textContent = `${hours}:${minutes}:${seconds}`
    }
    
    setInterval(displayTime, 1000);


  2. Your variable must be initalized/set again inside the function, so that each time your function is called, the latest time value gets initialized.

    
    function displayTime() {
        const time = new Date();
        const timeText = document.getElementById("time");
        const hours = time.getHours();
        const minutes = time.getMinutes();
        const seconds = time.getSeconds();
    
        timeText.textContent = `${hours}:${minutes}:${seconds}`
    }
    
    setInterval(displayTime, 1000);
    

    Here, each time the displayTime function is being called, the latest time values go into the variables, and hence the content gets changed to the latest time value.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search