How to wait for 3 seconds in ActionScript 2 or 3?

TheJavaGuy-Ivan Milosavljević picture TheJavaGuy-Ivan Milosavljević · Nov 8, 2011 · Viewed 57.2k times · Source

Is there any way to implement waiting for, say, 3 seconds in ActionScript, but to stay within same function? I have looked setInterval, setTimeOut and similar functions, but what I really need is this:

public function foo(param1, param2, param3) {
  //do something here
  //wait for 3 seconds
  //3 seconds have passed, now do something more
}

In case you wonder why I need this - it is a legal requirement, and no, I can't change it.

Answer

rid picture rid · Nov 8, 2011

Use the Timer to call a function after 3 seconds.

var timer:Timer = new Timer(3000);
timer.addEventListener(TimerEvent.TIMER, callback); // will call callback()
timer.start();

To do this properly, you should create the timer as an instance variable so you can remove the listener and the timer instance when the function is called, to avoid leaks.

class Test {
    private var timer:Timer = new Timer(3000);

    public function foo(param1:int, param2:int, param3:int):void {
        // do something here
        timer.addEventListener(TimerEvent.TIMER, fooPartTwo);
        timer.start();
    }

    private function fooPartTwo(event:TimerEvent):void {
        timer.removeEventListener(TimerEvent.TIMER, fooPartTwo);
        timer = null;
        // 3 seconds have passed, now do something more
    }
}

You could also use another function inside your foo function and retain scope, so you don't need to pass variables around.

function foo(param1:int, param2:int, param3:int):void {
    var x:int = 2; // you can use variables as you would normally

    // do something here

    var timer:Timer = new Timer(3000);
    var afterWaiting:Function = function(event:TimerEvent):void {
       timer.removeEventListener(TimerEvent.TIMER, afterWaiting);
       timer = null;

       // 3 seconds have passed, now do something more

       // the scope is retained and you can still refer to the variables you
       // used earlier
       x += 2;
    }

    timer.addEventListener(TimerEvent.TIMER, afterWaiting);
    timer.start();
}