Jump to content

setTimeout issue


freebsdntu

Recommended Posts

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; 
}

Link to comment
Share on other sites

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>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.