Saturday, October 30, 2010

JavaScript Delay Code Using setTimeout

One of the simplest ways to implement a delay in JavaScript is to use the “setTimeout” function. Actually it is the only way I would recommend as other ways may give unexpected result which I mention later in this tutorial. The catch here is that you cannot just use setTimeout on its own as you will see why later on.
The full syntax of the setTimeout function is as follows:

setTimeout("functionToCall()", 1000);

The parameters of this function are the function you plan to call and the delay in which the function should be called in milliseconds. It very important to note that the first parameter must be enclosed in quotes. If not the function is not going to work.

This code below is an example that shows an alert after waiting for five seconds

<script language="javascript">function hello(){alert("Hello, I have been delayed Five seconds");}</script><form><input type="button" value="Trigger Delay after 5 seconds" onClick="setTimeout('hello()',5000);"></form>

This is okay as long there is only one function but when you have several function working, the delay will still be there but the next function will continue to be processed without a noticeable pause.
For example in this code:
function hello(){//do some stuffsetTimeout('nextStep()',5000);// do more stuff}
Anything placed after the setTimeout function will be called even before the function “nextStep()” returns or is even called.

To simulate the sleep condition properly, with your JavaScript delay code, you can avoid this situation by running the code you intended to run after the delay from within the nextStep() function.
Here is an example to illustrate that.
function hello(){//do some stuffalert("Hello, anybody there?");setTimeout('nextStep()',5000);}function nextStep() {alert("Hello, I have been delayed Five seconds");} </script><form><input type="button" value="Run Job" onClick="hello()"></form>



No comments:

Post a Comment