# Javascript time delay



## malcolmd3111 (Aug 6, 2005)

I've just begun to study Javascript and am looking at "time delay". My learning style is to understand the simple things first and slowly build up expertise over time. I know there are the setTimeout() and setInterval() methods, however I cannot get them to work properly.

Required output:

Line of text... (1) 
{document.write("...data1...");}
time delay of set length (say 2 secs)
Line of text... (2) 
{document.write("...data2...");}
etc

Ultimately (I want to have a slide show of images running on a web site. Any help or guidance would be appreciated.

Thanks in advance.


----------



## php guy (Dec 17, 2004)

I would use timeOut for this. First, have the document.write parts in a function, then have timeOut call them after a specified time. Like...

```
setTimeout("data1()",2000);
function data1()
{
document.write("...data1...");
}
```
The 2000 means it will go to function data1 in 2000 miliseconds, or 2 seconds.You can change this to how ever long you want.


----------



## malcolmd3111 (Aug 6, 2005)

Thanks for the reply, php guy,
it looks good on paper, but the result is vapor!

Here is the exact code I want to see work prior to developing the actual code I intend to use, (images)

The value of 'i' is passed into the function 'data1' it is outputted to the screen + a newline. We exit the function, increment 'i' and call setTimeout again.... etc.

The result is a delay of 2 secs then the string ...data1...'5' is outputted to the screen. Any thoughts? Obviously I'm missing some key concept in the Javascript implimentation.

Thanks,

Malcolmd3111


----------



## php guy (Dec 17, 2004)

The lop you have starts 5 timeouts at once, which means they all end at the same time, not have 1 go for 2 seconds, then go back and start a second. Everything is working like it should, but when it gets to date(i), it runs through 5 times, each time with i=1 more then last, up untill 5. 5 is the last to go through, go the document.write clears everything befor it and outputs the string with i=5. The problem is document.write doesn't do what you want it to.


----------



## malcolmd3111 (Aug 6, 2005)

Thanks for the feedback..


----------



## php guy (Dec 17, 2004)

Oh, one thing i forgot, the reason it deletes everything is the document.write is used after the page is loaded, if it's used while it's loading, then the rest of the page will stay. This code would work for a slide show though, that is if you just want to change the src of an image, not document.write more in. If you wanted them to appear fter a while, you could use hidden divs and unhide them as time goes on.


----------

