Click to See Complete Forum and Search --> : looping with setTimeout()


toms
03-12-2003, 05:23 AM
I'm trying to get some image rollovers that are already on a page to automatically swap with a time delay, using setTimeout(). It works fine as a single sequence but when I try and loop it the browser freezes. I can see that rather than wait for each setTimeout to finish the loop is just triggering and infinite number of them concurrently, but how can I get around this?

Thanks in advance for any advice.

My code is...

// Define speech bubbles
bubble_off = new Image()
bubble_off.src = "images/spacer.gif"

bubble_01 = new Image()
bubble_01.src = "images/speechbar_licensing_bubble_01.gif"

bubble_02 = new Image()
bubble_02.src = "images/speechbar_licensing_bubble_02.gif"

bubble_03 = new Image()
bubble_03.src = "images/speechbar_licensing_bubble_03.gif"



// Define rollover faces
face_04_off = new Image()
face_04_off.src = "images/speechbar_licensing_off_04.gif"
face_04_on = new Image()
face_04_on.src = "images/speechbar_licensing_on_04.gif"

face_11_off = new Image()
face_11_off.src = "images/speechbar_licensing_off_11.gif"
face_11_on = new Image()
face_11_on.src = "images/speechbar_licensing_on_11.gif"

face_17_off = new Image()
face_17_off.src = "images/speechbar_licensing_off_17.gif"
face_17_on = new Image()
face_17_on.src = "images/speechbar_licensing_on_17.gif"


// For swapping image objects
function hiLite(imgDocID, imgObjName)
{
if( !document.images ) return
{
document.images[imgDocID].src = eval(imgObjName + ".src")
}
}



while (1) // loop infinitely
{
setTimeout('hiLite("face_04","face_04_on");hiLite("bubble","bubble_01")',1000);
setTimeout('hiLite("face_04","face_04_off");hiLite("bubble","bubble_off")',3000);

setTimeout('hiLite("face_11","face_11_on");hiLite("bubble","bubble_02")',5000);
setTimeout('hiLite("face_11","face_11_off");hiLite("bubble","bubble_off")',7000);

setTimeout('hiLite("face_17","face_17_on");hiLite("bubble","bubble_03")',9000);
setTimeout('hiLite("face_17","face_17_off");hiLite("bubble","bubble_off")',11000);
}

skriptor
03-12-2003, 06:11 AM
hi,
your while-statement start an endless row of timeouts. Try something like this instead:

var myStep = 0;
setTimeout('swap()', 1000 );

function swap() {
myStep++;
switch( myStep ) {
case 1:
hiLite("face_04","face_04_on");hiLite("bubble","bubble_01");
break;
case 2:
hiLite("face_04","face_04_off");hiLite("bubble","bubble_off");
break;

// add next steps

default:
myStep = 0;
break;
}
setTimeout('swap()', 2000 );
}

Good luck, skriptor

Vladdy
03-12-2003, 06:26 AM
Ever heard of setInterval() ?

toms
03-12-2003, 06:33 AM
works a treat - many thanks Skriptor!