|
CodingForums
Having trouble with scripting? Visit our help forum to get the answers you need.
This is a 
|
 |
setTimeout function
setTimeout, a method of the window object, basically delays
the execution of a function or statement until the specified time has
passed. The basic syntax of this function is:
setTimeout("expression", delaytime)
"expression" is the function/statement you want delayed, and
delaytime is the delay time, in milliseconds.
For example, this will output "Three seconds have gone!"
after 3 seconds.
document.three.hi.value=""
//simply clears the text box
function talk(){
setTimeout("document.three.hi.value='Three seconds have gone!'",3000)
}
<form name="three">
<input type="text" size="28">
<input type="button" value="Start" onClick="talk()">
</form>
Let's do a example that, by placing the setTimeout in a
special position, continuously writes to a box, incrementally itself every
second.
var c=0
document.go.timer.value=""
function count()
{
document.go.timer.value=c
c=c+1
setTimeout("count()",1000)
}
<form name="go">
<input type="text" name="timer" size="12">
<input type="button" value="Start" onClick="count()">
</form>
- A very important point is that the setTimeout method
executes count() after one second, but look at the place where setTimeout
is placed-inside count()! This will execute
everything within function count(), including setTimeout itself, every
one second. Basically, this forces the function to loop back and start at
the beginning each time it encounters this method. If you don't get it,
study it a little harder-you'll see it!
- The above function will run forever, until you reload
or leave. This is exactly the function we need to create a clock, since we
need a function that will continuously update itself. This function is so
important, because whenever you write something that needs continuous
refreshment, all you have to do is put a setTimeout function inside
another function and call it. Now, a little thought will tell us that we
can control this function, if we want to, so that it does not run forever-
namely, by putting it in an if-else-statement. Note that to get "1"
second, we used "1000". (1 millisecond*1000) equals 1 second.
Using setTimeout, we can implement a live clock. Ok, now
that we have all the tools, lets do just that.
|