freebsdntu Posted December 9, 2007 Share Posted December 9, 2007 Hello, everybody, I am a newbie here, a newbie to javascript as well. I would like to write a small clock that counts and displays like this:hour:minute:second. I got the display, yet the problem is that the clock does not count, I used the setTimeout method, I have no idea what went wrong, hope you guys can give me some hints. Thank you! Here are the codes clock.html <html> <head> <title> Javascript Clock </title> <script type = "text/javascript" src = "clock.js"> </script> </head> <body onload = 'setTimeout("clock()",1000)'> <div id = "time"> </div> </body> </html> clock.js var now = new Date(); var hour; var minute; var second; function clock() { hour = now.getHours(); minute = now.getMinutes(); second = now.getSeconds(); display_time(hour,minute,second); } function display_time(h,m,s) { var time = ""; if (h < 10) time += "0"; time += h; time += ":"; if (m < 10) time += "0"; time += m; time += ":"; if (s < 10) time += "0"; time += s; document.getElementById("time").innerHTML = time; } Quote Link to comment Share on other sites More sharing options...
phpQuestioner Posted December 9, 2007 Share Posted December 9, 2007 try this: <html> <head> <title> Javascript Clock </title> <script type="text/javascript"> function startTime() { var today=new Date(); var h=today.getHours(); var m=today.getMinutes(); var s=today.getSeconds(); // add a zero in front of numbers<10 m=checkTime(m); s=checkTime(s); document.getElementById('txt').innerHTML=h+":"+m+":"+s; t=setTimeout('startTime()',500); } function checkTime(i) { if (i<10) { i="0" + i; } return i; } </script> </head> <body onload="startTime()"> <div id="txt"></div> </body> </html> Quote Link to comment Share on other sites More sharing options...
freebsdntu Posted December 11, 2007 Author Share Posted December 11, 2007 thank you for your kind reply,phpQuestioner. Actually I have read that tutorial, my concern is still on what went wrong in my codes. Hope you guys can give me some hints. Quote Link to comment Share on other sites More sharing options...
phpQuestioner Posted December 11, 2007 Share Posted December 11, 2007 your "time" variable is null and your not including the "h", "m", or "s" variables in the "time" variable. you would be better off going with the example I provided you - learn from it and coil yours (sorry, but you really need to). Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.