如何等待3秒在ActionScript 2或3?ActionScript

由网友(白衣不染尘)分享简介:有没有什么办法来实现在ActionScript等待,比如,3秒,但保持同样的函数内?我看过的setInterval,setTimeout和类似的功能,但我真正需要的是这样的:Is there any way to implement waiting for, say, 3 seconds in ActionScrip...

有没有什么办法来实现在ActionScript等待,比如,3秒,但保持同样的函数内?我看过的setInterval,setTimeout和类似的功能,但我真正需要的是这样的:

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.

推荐答案

使用的Timer在3秒后调用函数。

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();
}
阅读全文

相关推荐

最新文章