View Full Version : how to cause a delay
shashgo
10-19-2002, 03:15 AM
Hi all,
if i have a script, say with a for loop, how do i cause a delay between each iteration of the loop.
So if the script is
for (i=0;i<20;i++)
{
document.img.src=i+".jpg";
}
how do i insert a delay after the img.src statement so that i can see each image 0-19)
ACJavascript
10-19-2002, 04:16 AM
Try this.. Not exactly what your asking for but might work just the same..
Set the setTimeout() to a slower level.. It will take longer for the for loop to go through the numbers.. Making it look as if theres a pause..
shashgo
10-19-2002, 04:26 AM
Hey AC,
So if I have
for (i=1;i<20;i++)
{
document.pic.src=i+".jpg";
setTimeout("",2000);
}
then the timeout will introduce a delay of 2 secs? oesnt the setTimeout method need to have a function name or some expression between the ""? And if it needs a function name and I enclose the for loop in a function, then wouldnt every call to the function by the setTimeout method cause the 'i' variable to reset to 1?
ACJavascript
10-19-2002, 04:29 AM
Yes and no..
the for loop takes care of the whole return to 1 thing.. and yes it needs to be in a function.. Like this..
function animateImages(){
for (i=1;i<20;i++)
{
document.pic.src=i+".jpg";
setTimeout("animateImages()",2000);
}
}
window.onload=animateImages;
shashgo
10-19-2002, 04:33 AM
AC,
Hmmm I had that before but I just ended up getting one image displayed. Let me try it again.
ACJavascript
10-19-2002, 04:36 AM
ya know what,, that might not work,, instead of having the setTimeout inside the for loop put it outside the for loop like this..
_______
function animateImages(){
for (i=1;i<20;i++)
{
document.pic.src=i+".jpg";
}
setTimeout("animateImages()",2000)
}
window.onload=animateImages;
joh6nn
10-19-2002, 05:55 AM
var imgI = 1;
function animateImages(){
if ( imgI < 20 ) {
document.pic.src = imgI++ + ".jpg";
setTimeout("animateImages()",2000);
}
}
window.onload=animateImages;
that should do it.
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.