ActionScript: Launch a function after a delay with setTimeout

There are different ways to launch a function after a delay:

  • With the enter frame event;
  • With the Timer class;
  • With a motion tween;
  • With the enter frame event and the getTimer() method;
  • And with the setTimeout function (See setTimeout help on Adobe);

How to master the setTimeout ?

  • First of all you must create a variable assigned to the setTimeout identifier;
var intervalIndentifier
  • The setTimeout function returns an identifier (uint) when you call this function. Save this identifier into the assigned variable;
// The hello function will be launched in 2000 ms
intervalIdentifier = setTimeout(hello, 2000)
function hello() {
    trace("function launched")
}
  • This identifier must be clear with the clearTimeout function in order to stop the setTimeout;
clearTimeout(intervalIdentifier)

NB:

  • If you want to launch a setInterval already launched don’t forget to clear the previous setInterval. In witch case the previous setInterval won’t be stopped;
  • The setTimeout function can’t be paused or resumed;
  • Assign one variable by one setTimout;
  • The setTimeout function is based on clock time not on frames time;
  • When you clear the setTimeout the closure function is not launched;
  • You don’t have to clear the setTimeout when the setTimeout is already finished;

Add parameters

The setTimeout function can receive one or several arguments. Those arguments are passed to the closure function.
To add arguments just add your arguments after the second parameter into the setTimeout function:
Obviously your closure function must have the same number of arguments.

intervalIdentifier = setTimeout(hello, 2000, "world", "www.benoitfreslon.com")
function hello(arg1, arg2) {
    trace(arg1, arg2)
}

Exemple:
[swf:/wp-content/uploads/2011/01/www.benoitfreslon.com-Launch-a-function-after-a-delay-with-setTimeout.swf 400 250]

Download source: www.benoitfreslon.com Launch a function after a delay with setTimeout.zip