Click to See Complete Forum and Search --> : beginner struggling with setTimeout


pauli
08-05-2003, 04:05 AM
Can anyone tell me why the 'menu' object becomes 'undefined' on the first recursive call ???

function displayNextImage(imagePlace,menu) {
var new_image = getNextImage();

menu.selectedIndex = ImageIndex;

document[imagePlace].src = new_image;
timerID = setTimeout('displayNextImage("'+imagePlace+'",menu)', interval);
}

menu is a 'select' object name passed from the HTML code initially. The idea is to display the next image and update a select list to show which image is being displayed.

As I said it works fine when first called, but dies at first recursive call.

Thanks

Gollum
08-05-2003, 05:05 AM
It's all to do with the scope of the setTimeout code.

when you say something like

timerID = setTimeout('displayNextImage("'+imagePlace+'",menu)', interval);

the javascript engine will wait out the interval and then 'run' the code. By this time, your function displayNextImage has long since exited and the menu argument is no longer valid.

It would be like saying this...

function callDisplay()
{
displayNextImage("someImage",menu);
}

as you can see, javascript has no idea what menu means in this context and so it complains.

So, you can do one of two things:
either make menu a global, or
use a function instead of a string. Functions inherit the context they are in and so the menu argument will still be in scope...

var timerID = window.setTimeout(function(){displayImage(imagePlace,menu);}, interval);

pauli
08-05-2003, 06:00 AM
Problem sorted the function way. Now I at least partially understand what's going on.

Thanks