Bachalo
Bachalo

Reputation: 7219

AS3 - reset delay on Timer

I have a private Timer object in an AS3 Class called _countDownTimer. When the class is instantiated, I also initialize the Timer once like so with some arbitrary delay

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

The problem is I need to change the delay time every time the Timer runs. So in another method I first redefine a private var _newDelayTime and then call startMyTimer() to redefine the delay and start the _countDownTimer.

My question is, should this work properly?

Do I ALSO need to instantiate a NEW _countDownTimer and re-add the listener every time I change the delay?

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

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

Upvotes: 0

Views: 521

Answers (2)

BadFeelingAboutThis
BadFeelingAboutThis

Reputation: 14406

You do not need (or want) to create a whole new timer object.

Setting the delay while the timer is running is perfectly acceptable.

Do note though, that setting the delay resets the timer, as per the documentation:

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

So, if the timer doesn't actually need to stop, take off the 1 repeat count when you instantiate (and start it), and then just change the delay whenever you need to.

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

Upvotes: 1

Ratty
Ratty

Reputation: 37

as I know, as3 Timer class is not precise in counting time... it depends on how fast listener function executes (waits until function finishes its job and continues counting). I prefer using greensock... but if it's not so important for you to have precise time than you can do something like this:

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


you can manipulate with _newDelayTime diffenetly... this should work properly and you wont need to re-add listeners

Upvotes: 1

Related Questions