View Full Version : JavaScript clock help

28th January 2007, 04:56 PM
Well I'm trying to learn how to do simple stuff in javascript and I made a clock with code from a book but it doesn't work. I've tried redoing it and changing stuff around but I still can't get it to work. I was hoping some one can help me. Thanks!


<BODY bgcolor="FFFFFF">

<h2><span id="time">00:00:00</span></h2>

<script language="javascript" type="text/javascript">

function update_time() {
var rightnow = new Date();

var hours = rightnow.getHours();
if (hours < 10)
var hourstring = "0" + hours.toString();
var hours = hourstring.toString();

var minutes = rightnow.getMinutes();
if (minutes < 10)
var minutestring = "0" + minutes.toString();
var minutestring = minutes.toString();

var seconds = rightnow.getSeconds();
if (seconds < 10)
var secondstring = "0" + seconds.toString();
var secondstring = seconds.toString();

var timestring = hourstring + ":" +
minutestring + ":" +

var timeplace = document.getElementById("time");
timeplace.childnodes[0].nodevalue = timestring;

<body onload="update_time()">


28th January 2007, 06:10 PM
that code has more errors than I care to count.
some issues (logic/syntax/convention)

var hours = hourstring.toString();probably would still work, but the line would be pointless then; it should be var hourstring = hours.toString();

the script (<script>...</script>) should be in the head part. (between the <head>...</head> tags)

it might be better if you had only one opening body tag for the ending one :P

timeplace.childnodes[0].nodevalue = timestring;mmm this should be simpler:
timeplace.innerHTML = timestring;

setTimeout("update_time()",1000)missing the semicolon at the end

mmmm there's probably some other stuff that I did to get it to work, but anyway, a simpler alternative:
I suggest you check a different source (http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock).

there are other sites too, but w3schools tutorials seem pretty good.

29th January 2007, 10:50 PM
Thanks a bunch! That fixed it and looking at other codes helped me a lot too.

*goes to try and make something more advanced*