Issue
I have made a simple clock using html,css and javascript but upon loading the page using the live server extension it is showing the correct time but is not changing the time by the second but the time does change upon reloading the page.
My Code
const d=new Date();
function time(){
let h=document.getElementById('hour');
let ho=d.getHours();
let m=document.getElementById('min');
let mi=d.getMinutes();
let s=document.getElementById('sec');
let se=d.getSeconds();
h.innerHTML=ho;
m.innerHTML=mi;
s.innerHTML=se;
setTimeout(time, 1000);
}
time();
Solution
Cache your elements up front so you're always accessing the DOM for each of them in the function.
Move the creation of the new date into the function.
Maybe use
textContentinstead ofinnerHTMLas it is just text you're adding.
Edit: I added a little padding function that prefixes a zero to any number that only has one digit.
const hour = document.getElementById('hour');
const minutes = document.getElementById('minutes');
const seconds = document.getElementById('seconds');
function pad(n) {
return String(n).length === 1 ? `0${n}`: n;
}
function time() {
const d = new Date();
hour.textContent = pad(d.getHours());
minutes.textContent = pad(d.getMinutes());
seconds.textContent = pad(d.getSeconds());
setTimeout(time, 1000);
}
time();
.container { font-size: 2em; }
<div class="container">
<span id="hour"></span> :
<span id="minutes"></span> :
<span id="seconds"></span>
</div>
Additional documentation
Answered By - Andy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.