David StillerDavid Stiller's blog

Luck is the residue of good design.

setTimeout() "Gotcha" in Class Files

Posted Tuesday, January 16, 2007 8:27:19 AM by David Stiller

The setTimeout() function is a valid citizen in the realm of ActionScript 2.0; it was simply left off the roster for some reason, so you won’t find it in the documentation.  It works very much like its JavaScript counterpart and is less cumbersome to use than setInterval() for triggering a single delayed action.  You can reference setTimeout() just fine in timeline code, but I found an unexpected problem when employing this function in a class file.  Its presence halted the compile process and caused all sorts of misleading errors, such as the idea that Stage can’t be reference in a class file (it certainly can).  Is there a workaround?  Yes.

An answer, short and sweet

If you find yourself desiring setTimeout() inside a custom class, use the array access operator to refer to the function.

_global["setTimeout"]

This one of the techniques you can use to reference objects dynamically — and even functions are objects.  To actually trigger the function, you need to add the parentheses, and those come right after the closing bracket.  At that point, it’s business as usual.

_global["setTimeout"](functionToTrigger, 1000);

How it works

To be honest, I can’t explain the “how” especially well, in this case.  The setTimeout() function was left out of the documentation and the intrinsic class definition files, which means the compiler (sometimes) doesn’t know it exists.  Why this only happens in external class files is beyond my grasp.  But the solution is easy, enough.  :)  I had to experiment with which object to use as the prefix (I tried _root, a passed-in reference to the main timeline, and this, but suddenly _global occurred to me, and that’s what works).

Category tags: Flash

See Community MX content by David Stiller