Jump to content

[SOLVED] Js basics question


blackcell

Recommended Posts

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

source: http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock

 

First, I am very new to javascript. I want to get to know js as well as php (where I don't have to grab examples from free script sites)

I have a few questions on how JS works.

 

First, how does the clock update automatically with every second?

Second, how does the <div> tag work?  Say if I wanted to insert the clock in a table, would I have to have the:

<div id="txt"></div>

like this:

...

<td><div id="txt"></div></td>

...

Link to comment
https://forums.phpfreaks.com/topic/92301-solved-js-basics-question/
Share on other sites

 

The script gets the initial day and time from your computer. Then it uses setTimeout to create a timing event that update the text in your div every 1/2 a second. The DIV tag does not matter; as long as whatever element you want to display the time in; has an id of txt and the element is capable of displaying content in it; then you could use any element.

 

you could just do something like this:

 

<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()">
<table>
<tr>
<td id="txt"></td>
</tr>
</table>

 

or if you don't want to take up any space at all in your page; I suggest using a span, like so:

 

<span id="txt"></span>

I see...

Now, is the setTimeout some sort of function that executes a piece of script after the specified amount of Time?

If this is true it makes sense how it continually updates because the function loops through itself ever 1/2 second using the settimeout right?

I see...

Now, is the setTimeout some sort of function that executes a piece of script after the specified amount of Time?

If this is true it makes sense how it continually updates because the function loops through itself ever 1/2 second using the settimeout right?

 

Exactly Right ;)

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.