Was wondering where I am going wrong with this snippet of code, basically the startTime() only gets run once and thats it so the clock doesnt update. Can anyone advise how I can fix this?
JS
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;
}
HTML
<body onload="startTime()">
<p>Date</p>
<?php echo date("d/m/y"); ?>
<p>Time</p>
<div id="txt"></div>
Link http://bit.ly/IC9ohX
You just have a problem with the scoping of your functions.
Short solution: Change
to this.
Explanation:
The function
startTimeis defined within the function forwindow.onloadand is only visible within that function (and functions within it)!In your code JavaScript waits the 500ms and then tries to execute the code
startTime(). It searches for the functionstartTimein the global scope (which is the execution scope ofsetTimeout) and can’t find any reference, thus resulting in an error and your code not working.My code passes the reference of the function
startTimetosetTimeout. This way the engine does not have to search for the handler and can’t fail at that point. At the point wheresetTimeoutis called, you are in the scope ofwindow.unload, thus the engine knows of the functionstartTimeand can cope with the handler passed tosetTimeout.