Back
Next
In JavaScript with setTimeOut function, we have to remember that JavaScript execution is
*not* stopped. So even though we are setting an event to take
place in the future, our script continues to run. So our while
loop will keep executing and changing the images, there is no
pause.
Creating time delays with SetTimeOut in JavaScript
There are two ways of creating time delays in JavaScript. The first is more simple and
will simply wait for a specified amount of time before executing a JavaScript function. The second does
the same but will repeatedly execute the JavaScript function.
Note, most browsers have a minimum delay length of between 25 and 75 ms. If a shorter delay is
specified, the actual delay will be the minimum delay length. Even with higher numbers, the delay
is never perfect. Most web browsers will take slightly longer than the time we ask for, typically
just a few milliseconds error. Some may correct their errors over time with interval timers. Also
note, setting many timers with short delays on one page will cause the web browser to become slow and
somewhat unresponsive. Three or four timers is usually the reliable limit.
The first method uses a window method called setTimeout() in JavaScript. The
setTimeOut() method waits for a
specified number of milliseconds then executes the specified code. The code can either be a
direct reference to a JavaScript function, or it can be a string that will be evaluated as if it contained source code.
Syntax of JavaScript SetTimeOut() Function
window.setTimeout( referenceToYourFunction , timeInMilliseconds );
Example of JavaScript SetTimeOut() Method
<img id="banner">
<SCRIPT LANGUAGE="JavaScript">
<!--
var banner=0;
function changingBanner()
{
if(banner<5){
var img ="";
img = "../images/banner" + banner + ".jpg";
document.getElementById("banner").src= img;
document.getElementById("banner").alt=
"JavaScript Tutorial, JavaScript SetTimeOut()";
banner++;
if(banner==5){
banner=0;
}
}
//this JavaScript setTimeOut() function will recall the
//changingBanner() after one second
setTimeout("changingBanner()", 3000);
}
changingBanner();
-->
</SCRIPT>
Output of JavaScript SetTimeOut() Example
Back
Next
|