I have a Cairngorm-based application that polls a server for data every few seconds. To do this I have a command that initiates the server request, and in the result handler I set a timeout. When that timeout is up, I dispatch the event that is responsible for kicking off the command in the first place. It looks something like this:
public class PollServerCommand { public function execute(event:CairngormEvent):void { // Create and call delegate } public function result(data:Object):void { // Process data... setTimeout(2000,poll); } private function poll():void { var pollEvent:PollEvent = new PollEvent(); pollEvent.dispatch(); } }
This results in lots of commands being created, but in theory the garbage collector should be cleaning up the old ones every so often. Well, that’s not really the case. While profiling my app, I noticed that every polling command I created stayed in memory. The solution? Swapping out the calls to setTimeout for instances of the Timer class like so…
public function result(data:Object):void { var pollTimer:Timer = new Timer(2000,1); pollTimer.addEventListener(TimerEvent.TIMER,poll); pollTimer.start(); } private function poll(event:TimerEvent):void { var pollEvent:PollEvent = new PollEvent(); pollEvent.dispatch(); }
I’ve always known that the Timer class was preferred over setTimeout, but now I know why. Can anyone from the Flash Player Team shed some light on why setTimeout is keeping these objects alive?
74p1y7