AS3 - 定时器重置延迟

AS3 - reset delay on Timer

我在 AS3 Class 中有一个名为 _countDownTimer 的私有 Timer 对象。 当 class 被实例化时,我也像这样用一些任意延迟初始化定时器一次

_countDownTimer =new Timer(10000, 1);
_countDownTimer.addEventListener(TimerEvent.TIMER, onCue,false,0,true);

问题是每次定时器运行时我都需要更改延迟时间。 所以在另一种方法中,我首先重新定义了一个私有变量_newDelayTime,然后调用startMyTimer()重新定义延迟并启动_countDownTimer

我的问题是,这应该正常工作吗?

是否还需要在每次更改延迟时实例化一个新的 _countDownTimer 并重新添加侦听器?

private function startMyTimer():void{
    _countDownTimer.reset();
    _countDownTimer.stop();
    _countDownTimer.delay=_newDelayTime;
    _countDownTimer.start();
}

private function onCue(e:TimerEvent):void{
    trace('do stuff');
}

据我所知,as3 计时器 class 在计算时间时并不精确...这取决于侦听器函数执行的速度(等待函数完成其工作并继续计数)。我更喜欢使用 greensock ......但是如果精确时间对你来说不是那么重要,那么你可以这样做:

private function onCue(e:TimerEvent):void
    {
    trace(e.currentTarget.delay);
    _newDelayTime = Math.round(Math.random() * 999) + 1;
    startMyTimer();
    trace('do stuff');
}


你可以用 _newDelayTime 不同地操作...这应该可以正常工作,你不需要重新添加监听器

您不需要(或不想)创建一个全新的计时器对象。

在计时器为 运行 时设置延迟是完全可以接受的。

不过请注意,根据 documentation:

设置延迟会重置计时器

If you set the delay interval while the timer is running, the timer will restart at the same repeatCount iteration.

因此,如果计时器实际上不需要停止,请在实例化(并启动它)时取消 1 重复计数,然后在需要时更改延迟。

_countDownTimer.delay=_newDelayTime; //no need to reset/stop/restart