16 October 2008

Why you shouldn't use setInterval

Some days ago, I was finishing a title screen for my coming game.
It's pretty simple : wait 3 sec then jump to next frame.

To do that I mainly use setInterval on web based Flash :
idInterval = setInterval( myFunc, 3000)
and, on myFunc :
gotoAndPlay(nextone)
clearInterval(idInterval)
idInterval = null
delete idInterval

Well...as you should know, it's really important to clean everything not wanted when you finished a job. Since AS's object haven't a destructor, I do it on onUnload.
It works! ... but not when you use an interval.

Yes, I don't know why (a internal listener not cleaned ?) but onUnload isn't called when you have an interval EVEN when you nulled and deleted it (see below).

So, I replace my setInterval with
onLoad :
initTimer = getTimer( )
onEnterFrame :
if ( (getTimer()- initTimer) >= 3000 ) gotoAndPlay(nextone)

As always, if you have some hints, I'm here!

2 comments:

Fernando said...

Hi, I found the same issue a time ago. I solve using calling setInterval passing the object where intervalId and function are defined. Something like this idInterval=setInterval(this, "myFunc", 3000);
Have you tried that way?

William Gregoire said...

Hi,
it's strange because it's the way I used it in fact...
I'll retry just in case I made a mistake.
Thanks for the hint anyway.