I have the following code in a class function :
public function foo():void
{
var timer:Timer = new Timer(10000,1);
timer.addEventListener(TimerEvent.TIMER_COMPLETE,onTimerComplete);
timer.start();
}
public function onTimerComplete(e:TimerEvent):void
{
// do stuff
}
The above code works most of the time but my concern is what happens if timer gets garbage collected? Is it possible that onTimerComplete will never fire because there are no other references to timer?
I know timer has an internal list of handlers but that won’t keep it from being GC’ed.
There are some references on the web to running timers never being garbage collected, e.g.:
but I haven’t been able to find an authoritative source.
Probably best to not rely on this special behavior and instead make
timera class-level variable, though.Answers suggesting that event listeners are keeping the timer from being garbage collected are incorrect. The reference is from the timer to the listener function (
onTimerComplete), so if the timer is reachable then the listener function won’t be garbage collected, but not vice versa. This is easily tested:Output: