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
Your variable must be initalized/set again inside the function, so that each time your function is called, the latest time value gets initialized.
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.