Timing Functions

In order to provide 'animation' we need to change the position of something over a period of time.

We can accomplish that by changing the top and/or left properties of an object using javascript.

We can use that javascript with a timing loop to change the position of an object at appropriate intervals.

Javascript provides a couple of timing functions setInterval() and setTimeout().

We will use the setTimeout() function

The setTimeout() function takes two arguments,

For example, setTimeout('fred()',20) will execute the function fred() every 20/1000 of a second or 50 times per second.

Creating a loop

If we place a setTimeout('looper',100) inside the function looper() we effectively create a loop that updates 10 times a second.

<head>
<script type='text/javascript'>
  var x=0;
  function looper(){
     x=x+1;
     document.forms[0].elements[0].value=x;
     setTimeout('looper()',100);
}
</script>
</head>
<body onload='javascript:looper();'>
<form>
<input type='text' />
</form></body>
Simple Countdown An example using the setTimeout() function to build a Countdown display.

Simple Clock An example using the setTimeout() function to build a javascript clock.

Exercise
Change the Simple Countdown example so it counts down from 10 but waits two seconds between 'ticks'.