Delaying a function call in Flash AS3.
In a number of Flash projects we've done at JMX2 (shameless plug), I've run into the situation where I simply wanted to delay the actual execution of a function. Sometimes it was to tweak an animation so its pacing felt right. Often times I wanted to delay a sound clip by a few beats so that it gave the proper timing to the scene.
After writing the same code a number of times, I decided to encapsulate that whole process into a class called delayedFunctionCall. It's not the most elegant name perhaps, but it's descriptive.
I've found myself using on nearly every project since I wrote it. Maybe you'll find it useful too.
What is delayedFunctionCall?
This ActionScript 3 (aka AS3) class is pretty simple. You pass it a function and a number of milliseconds to wait for that function to be executed.
How to use delayedFunctionCall
First you'll need to download the package. Once you've got it, place it in your Flash project's class path in the com/jmx2/ directory. In your ActionScript file or Flash movie, import the package.
Now you've got the housekeeping out of the way, to delay a function, create a new delayedFunctionCall and pass in the name of the function you want to delay as the first parameter. The second parameter is the number of milliseconds you want to wait until the function should execute.
Below is an example of how you'd use it.
import com.jmx2.delayedFunctionCall;
// the time vaule is in milliseconds, 1000 milliseconds = 1 second
new delayedFunctionCall(myFunctionToStartLater, 3500);
function myFunctionToStartLater():void {
trace("This function executed 3 and a half seconds after it was called by using the delayedFuctionCall function.");
}
Pretty simple.
Get the code
Need to delay some functions of your own? Don't delay... (Sorry for that!) just click here to download your own copy of delayedFunctionCall. Use it in peace and harmony.