actionscript 3.0如何设置时间延迟

use*_*641 2 flash timer delay actionscript-3

有没有办法延迟我的功能3秒.除了等待3秒然后执行一个函数,我希望它等待3秒然后执行它将在3秒前完成的功能.

我可能在最后一句话中没有意义,但这是一个例子:

防爆.走路,然后你有一个跟随者你做了完全相同的事情,除了延迟3秒.

提前致谢.

xdl*_*xdl 8

AS3中的函数是第一类成员,这意味着它们可以作为参数传递.设置延迟的一种方法是定义一个'延迟'函数,如下所示:

function delayedFunctionCall(delay:int, func:Function) {
    trace('going to execute the function you passed me in', delay, 'milliseconds');
    var timer:Timer = new Timer(delay, 1);
    timer.addEventListener(TimerEvent.TIMER, func);
    timer.start();
}


function walkRight() {
    trace('walking right');
}

function saySomething(to_say:String) {
    trace('person says: ', to_say);
}

//Call this function like so:

delayedFunctionCall(2000, function(e:Event) {walkRight();});

delayedFunctionCall(3000, function(e:Event) {saySomething("hi there");});
Run Code Online (Sandbox Code Playgroud)

你需要延迟的函数需要用这样的匿名函数"包装",因为.addEventListener方法希望传递一个只有一个参数的函数:Event对象.

(但您仍然可以指定要传递给匿名函数中的延迟函数的参数.)

  • 这是一个好点 - 也应该摆脱事件监听器:`delayedFunctionCall(2000,function(e:Event){e.currentTarget.removeEventListener(e.type,arguments.callee); walkRight();});` (2认同)