0

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

0

2 Answers 2

5

You just have a problem with the scoping of your functions.

Short solution: Change

t=setTimeout( 'startTime()',500);

to this.

t = setTimeout( startTime, 500 );

Explanation:

The function startTime is defined within the function for window.onload and 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 function startTime in the global scope (which is the execution scope of setTimeout) and can't find any reference, thus resulting in an error and your code not working.

My code passes the reference of the function startTime to setTimeout. This way the engine does not have to search for the handler and can't fail at that point. At the point where setTimeout is called, you are in the scope of window.unload, thus the engine knows of the function startTime and can cope with the handler passed to setTimeout.

Sign up to request clarification or add additional context in comments.

Comments

0

setTimeout waits the specified amount of time, does its job, then stops. You want setInterval, which repeats the same job indefinitely.

EDIT: Sorry, I brainfarted while reading your code. Didn't realize you were calling setTimeout at the end of the function.

There's still a valid use case to use setInterval instead of setTimeout though. Suppose your function itself takes 2 milliseconds to complete. Rather than updating every half a second, your clock is actually updating every 502 milliseconds. So, after 100 iterations, it will be executing .2 seconds off from where it should be. It's probably not noticeable, but a setInterval of 1 second would make your clock actually appear to tick every second, as it should.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.