Apache flex 在一帧之后执行函数的最佳方法是什么?

Apache flex 在一帧之后执行函数的最佳方法是什么?,apache-flex,actionscript-3,flash,timing,Apache Flex,Actionscript 3,Flash,Timing,对于Flash Player 9+的ActionScript3,在一帧之后调用“一次性”函数的最佳方式是什么 我知道Timer类及其用法,以及FlexUIComponents上的callLater方法(在这种情况下,通过查看源代码,它看起来不是很有效)。我还知道setTimeout(在flash.utils中) Timer类和setTimeout实用程序都是基于时间的,那么我们如何保证函数在恰好一帧后被调用呢 从我有限的测试来看,传递给setTimeout的函数似乎只在至少一帧后执行(尝试将延迟

对于Flash Player 9+的ActionScript3,在一帧之后调用“一次性”函数的最佳方式是什么

我知道Timer类及其用法,以及FlexUIComponents上的callLater方法(在这种情况下,通过查看源代码,它看起来不是很有效)。我还知道setTimeout(在flash.utils中)

Timer类和setTimeout实用程序都是基于时间的,那么我们如何保证函数在恰好一帧后被调用呢

从我有限的测试来看,传递给setTimeout的函数似乎只在至少一帧后执行(尝试将延迟设置为0)。但这并不能保证


当然,我们可以监听Event.ENTER_FRAME events(从DisplayObject输入帧事件),但对于一次性延迟的函数调用来说,这似乎有些过分。

一种方法是查看项目每秒设置了多少帧,并让setTimeout函数在该设置内延迟1帧时间


因此,如果您的项目设置为每秒24帧,您将在setTimeout中延迟42毫秒。

Flex旨在抽象出Flash播放器基于帧的特性,这样您就不会发现对您的问题有多大帮助。最好的方法是按照您的建议收听输入帧。如果这太过分了(我不知道你为什么这么认为),你可以创建一个helper类,它将DisplayObject和函数作为参数,自动为你添加/删除ENTER\u FRAME事件监听器

public class NextFrameCommand() {

    private var functionToCall : Function;

    public function NextFrameCommand(dObj: DisplayObject, func : Function) {
        functionToCall = func;
    }

    public function start() : void {
        dObj.addEventListener(Event.ENTER_FRAME, onEnterFrame);
    }

    private function onEnterFrame(e : Event) : void {
        e.target.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
        functionToCall.call();
    }

}

我还没有测试过该代码,但希望您能理解……

使用Theo和brd6644提供的解决方案,我是带着这个来的。它允许多个函数(带参数)排队并在下一帧按顺序执行

var timerSprite:Sprite = new Sprite();

timerSprite.addEventListener(Event.ENTER_FRAME, oneFrameHandeler);

function oneFrameHandeler(e:Event):void
{
   timerSprite.removeEventListener(Event.ENTER_FRAME, oneFrameHandeler);
   timerSprite = null;

   trace("one frame later!")
}
public class DelayedFunctionQueue
{
    protected var queue:Array;
    protected var dispatcher:Sprite;

    public function DelayedFunctionQueue()
    {
        queue = new Array();
        dispatcher = new Sprite();
    }

    public function add( func:Function, ... args ):void
    {
        var delegateFn:Function = function():void
        {
            func.apply( null, args );
        }
        queue.push( delegateFn );
        if ( queue.length == 1 )
        {
            dispatcher.addEventListener( Event.ENTER_FRAME, onEF, false, 0, true );
        }
    }

    protected function onEF( event:Event ):void
    {
        dispatcher.removeEventListener( Event.ENTER_FRAME, onEF, false );
        queue = queue.reverse();
        while ( queue.length > 0 )
        {
            var delegateFn:Function = queue.pop();
            delegateFn();
        }
    }
}

可能对某些人有用。

输入帧并不过分-像这样的东西既短又简单

addEventListener(Event.ENTER_FRAME, function(e:Event):void
{
    removeEventListener(Event.ENTER_FRAME, arguments["callee"]);
    onceOffFunction();
}

在同一时间发布的Oops中,我认为最好的应该是您的结构(可重用性),但在我的示例中,自动实例化了一个虚拟精灵(我只是想快速说明这个想法)。这个答案没有添加任何内容,多年前已经由其他人提供,答案被接受。你在补充什么还没说的?