Clock example using Date()

We can load the initial values into the <span id="clock"></span> tag using the body tag's onLoad event.

<body onLoad="init()">
<span id="clock"></span>

In this case the init() function has been defined in the head area as follows:

<script language="javascript" type="text/javascript">
function init(){
    var clock = document.getElementById("clock");
    clock.innerHTML = new Date();
}
</script>

This will load the current date (at least what the user's computer thinks the date is!) into the span tag. But to make it a clock rather than a time stamp we have to at least update the time, so we will need a function called "setTimeout()" to update the time every second.

<script language="javascript" type="text/javascript">
function init(){
    var clock = document.getElementById("clock");
    clock.innerHTML = new Date();
    setTimeout('init()',1000);
}
</script>

By adding this to our init() function, we will be telling the browser to re-call the init() function in 1000 milliseconds, which is one second in the future. We are asking the init() function to call itself recursively rather than define another identical function called something like 'update()'.


Loading date information...