Monday, December 20, 2010

Terrible Timers!!!

I was working on a flash application today, which unfortunately involved a few timers. The code was in AS 2.0 While the application was running, I noticed something was causing a hurdle to the smooth running of the application. I meddled with the whole affair a lot, and finally after an effort of an hour or so, I inferenced that there was a timer which was not getting cleared off, and was causing trouble to the application.


Its useful to use timers in our applications, but at the same time, its really important to "destroy" them after their usage.


Let us begin with a simple example of timers.

var simpleTimer:Number;
simpleTimer = setInterval(simpleFunction, 2000);

function simpleFunction( )
{
       clearInterval(simpleTimer);
       trace("Timer called !");
}

Now let us suppose, we call this timer multiple times in our application. There are chances in which the instances of the timers are still active even when we dont use them. This could be majorly because, the old instance of the timer is not cleared out, and a new is already into action. Another reason is related to the first one, as in, if there are multiple calls to a function which generates any timer, and the application runs fast, then before the first timer gets cleared, succesive calls to that function, re-start the timer again, before destroying the previous timer. Hence , its always recommeded to clear the timer first before starting it afresh.


Revised code for the above simple program, is as follows:

var simpleTimer:Number;
clearInterval(simpleTimer);
simpleTimer = setInterval(simpleFunction, 2000);

function simpleFunction( )
{
       clearInterval(simpleTimer);
       trace("Timer called !");
}


clearInterval(simpleTimer)  before starting the timer again, solves the problem of unused active timers.

No comments:

Post a Comment