const pad = num => String("0"+num).slice(-2);
window.addEventListener("load", function() {
const container = document.getElementById('txt');
const tId = setInterval(function() {
const today = new Date();
const h = pad(today.getHours());
const m = pad(today.getMinutes());
const s = pad(today.getSeconds());
container.textContent = h + ":" + m + ":" + s;
}, 500)
})
<div id="txt"></div>
Problem :
I have a 24 hour clock function in the top right-hand corner of my site. It loads and displays everything fine, apart from when it reaches “00:00:01”, the first zero is missing from the hour counter. E.g. it only shows “0:00:01” until it reaches “10:00:00”. Not sure what I am missing.
See image for example:
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i
}; // add zero in front of numbers < 10
return i;
}
<body onload="startTime()">
<div id="txt"></div>
Comments
Comment posted by jonrsharpe
You don’t use
Comment posted by mplungjan
And when you do you may need
Comment posted by Roko C. Buljan
<script>
Comment posted by bron
or check the length of the number
Comment posted by mplungjan
@bron You have mistakes. It is === 1 and not = 1 (assignment) – if you must, then