[Javascript] A loop for this script?

Andrew Clover and-babble at doxdesk.com
Sat Jul 2 09:11:57 CDT 2005


Roland Dong <rdong at advance.net> wrote:

> TIMER=setTimeout('document.getElementById(ids[this.cellIndex]).style.visibil
> ity="hidden"', 500)

> Then the code stops working and complains that "ids is not defined".

Naturally. You've passed a string in to setTimeout, not a function. As 
it's a string it won't be executed in the same scope as your call to 
setTimeout, but will bind variables at run-time. At which point it is 
not inside your startList function, so the local variable 'ids' is not 
in scope.

Plus timeout strings are executed in the window object, not any Element. 
So 'this' will be 'window' at run-time and 'this.cellIndex' won't exist.

Supposedly you should be able to pass parameters for a timeout callback 
as extra parameters to setTimeout, but in practice it doesn't work 
cross-browser.

A quick fix would be to precalculate the id and put it in the string:

   var id= ids[i];
   var f= 'document.getElementById("'+id+'").style.visibility= "hidden"';
   var timer= window.setTimeout(f, 500)

It's pretty ugly, but timeouts are troublesome in general, and deploying 
them for dropdowns in a usable way is tricky. Consider for example what 
happens when the users mouses away from element A and then back again in 
under 500ms.

PS. Don't use "for (x in a)" to iterate over an Array - it may not 
behave in the way you might expect.

PPS. Also please avoid top-posting! :-)

-- 
Andrew Clover
mailto:and at doxdesk.com
http://www.doxdesk.com/



More information about the Javascript mailing list