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
https://forums.phpfreaks.com/topic/80877-settimeout-issue/
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
https://forums.phpfreaks.com/topic/80877-settimeout-issue/#findComment-410308
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.