var timeoutID = setTimeout(function, milliseconds, [arg1, arg2, ...]) var intervalID = scope.setInterval(function, milliseconds, [arg1, arg2, ...])
The arguments are optional, and are passed to the named function.
Frame object, window object
The SetInterval method repeatedly calls the function with a fixed time delay between each call.
When passing arguments to a function within a setTimeout or setInterval call, wrap it in an anonymous function, e.g. this.setTimeout(function(){myfunc(a,b,c)}, 100)
Never pass a simple or concatenated string as the first argument of a setTimeout or setInterval call. A string will be evaluated in exactly the same way as an eval call, including the associated performance impact. For this reason, pass an anonymous function or a callback instead.
Global this problem: Code executed by setInterval() runs in a separate execution context than the function from which it was called. As a consequence, the this keyword for the called function is set to the window (or global) object, it is not the same as the this value for the function that called setTimeout. 1
<SCRIPT LANGUAGE="JavaScript">
function displayAlert() {
alert("5 seconds have elapsed since the button was clicked.")
}
</SCRIPT>
<BODY>
<FORM>
Click the button on the left for a reminder in 5 seconds;
click the button on the right to cancel the reminder before
it is displayed.
<P>
<INPUT TYPE="button" VALUE="5-second reminder"
NAME="remind_button"
onClick="timerID=setTimeout('displayAlert()',5000)">
<INPUT TYPE="button" VALUE="Clear the 5-second reminder"
NAME="remind_disable_button"
onClick="clearTimeout(timerID)">
</FORM>
</BODY>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
var timerID = null
var timerRunning = false
function stopclock(){
if(timerRunning)
clearTimeout(timerID)
timerRunning = false
}
function startclock(){
// Make sure the clock is stopped
stopclock()
showtime()
}
function showtime(){
var now = new Date()
var hours = now.getHours()
var minutes = now.getMinutes()
var seconds = now.getSeconds()
var timeValue = "" + ((hours > 12) ? hours - 12 : hours)
timeValue += ((minutes < 10) ? ":0" : ":") + minutes
timeValue += ((seconds < 10) ? ":0" : ":") + seconds
timeValue += (hours >= 12) ? " P.M." : " A.M."
document.clock.face.value = timeValue
timerID = setTimeout("showtime()",1000)
timerRunning = true
}
//-->
</SCRIPT>
</HEAD>
<BODY onLoad="startclock()">
<FORM NAME="clock" onSubmit="0">
<INPUT TYPE="text" NAME="face" SIZE=12 VALUE ="">
</FORM>
</BODY>
clearTimeout method
See also: