Javascript: a simple clock


Your local time!

And this is the HTML page:

<html><script language="JavaScript">
function mytime() {
var x=new Date();
h=x.
getHours();
m=x.
getMinutes();
s=x.
getSeconds();
if(s<=9) s="0"+s;
if(m<=9) m="0"+m;
if(h<=9) h="0"+h;
time=h+":"+m+":"+s;
document.rclock.rtime.value=time;
setTimeout("mytime()",1000); }
//-->
</script>

<BODY onload="mytime()"><center>
<H3>Your local time!</H3>
<form name="rclock">
<table border="2">
<input type="text" name="rtime" size="7">
</table>
</form>
</center>
</body>
</html>

Ok, when you load this page (Load event and OnLoad event-handler), the browser perform the 'mytime' script. So, let's see this script:

x=new Date()

Well, Javascript has some built-in objects, such as boolean, array or date. We shouldn't talk about objects, but we should say objects' classes. In fact, Date() isn't a real single object, but a set of objects having the same properties. So you have to build an instance of that object by means of the new operator. In the above line, you are saying: 'please browser, built a new object which belongs to the Date() class...its name will be: x'. In other words, 'x' (but you can choose any name you prefer) is the name of the new object. In addition, 'x' is a variable. In fact you define explicity 'x' as a variable, by means of the var statement.

The Date() object, has several methods, such as getHours, getMinutes or getSeconds. However there are other methods. You can't retrieve a date before 1 January 1970.

h=x.getHours() means: 'get the hour by means the getHours() method applied to the x object, and then put (assign to) that value to the variable h'.

The '+' symbol, is an operator helpful to handle strings. You can paste pieces of strings by means of the '+' symbol. For example: 'this is a string' + ':' 'Hello' + 'world...' means:

'this is a string: Hello world...'

Finally:

tick=setTimeout("mytime()",1000)

SetTimeout is a method of the Window object. It calls a function after a certain number of milliseconds (in this case after 1000 milliseconds, or, in other words, after a second). So setTimeout calls the 'mytime' function each second.


Index           Home  Back       About  Contact us!

Copyright (c) 1998-2006 Wowarea