Wednesday, August 5, 2009

Dangers of setTimeout in Flex

So, after fighting a memory leak in Flex for the last week, I have learned a valuable lesson that hopefully will help. The setTimeout method in Flex is dangerous. It turns out that it is not automatically garbage collected when your Flex app is in operation (indeed, I don't even know of a manual way to force it to be garbage collected). Here was my situation:

I needed a clock that would increment itself every second. To do this, I created a little method called runClock that simply updated the time on the clock face and then had a setTimeout(1000, runClock). Without realizing what I had done, I was now creating a new Object every second that was never reclaimed by the Flex garbage collection process.

What I should have done (and what I now have) is a Timer. I have simply set my Timer to fire every 1000 ms, to call runClock and to run indefinitely. Problem solved and memory leak patched!