Displaying a Javascript clock in HTML
Displaying a Javascript clock in HTML
Here is jsfiddle: http://jsfiddle.net/Xx2ce/3/
First of all you want to use setInterval
instead of setTimeout
Also just fixed other bugs with your code
Here is the code:
function startTime() {
var d=new Date();
var h=d.getHours();
var m=d.getMinutes();
var s=d.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById(txt).innerHTML = Todays current time is: +h+:+m+:+s;
}
function checkTime(i) {
var j = i;
if (i < 10) {
j = 0 + i;
}
return j;
}
setInterval(function() {
startTime();
}, 500);
for HTML all you need is this:
<p id=txt></p>
and the clock will tick… magic eh? ))
You could do something like this:
<!DOCTYPE html>
<html>
<body>
The time is:<div id=txt></div>
<script>
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(function(){startTime()},500);
}
function checkTime(i) {
if (i<10) {i = 0 + i}; // add zero in front of numbers < 10
return i;
}
startTime();
</script>
</body>
</html>
Displaying a Javascript clock in HTML
Here you Go:
<body onload=startTime()>
or
window.onload=startTime;
Hope this helps.