I just came across a nasty "feature" of the setInterval function which almost gives me mystical feelings. This is not for the weak hearted. We'll be entering an area of phantom functions and lost pointers:
Start the example and read on.
We have the following setup:
Movieclip "MAIN" is a simple container, its purpose is to load additional movieclips into other levels. I would call this a standard setup which occurs more than once in Flash history.
Movieclips "A", "B" and "C" are subclips that could work also standalone, so they contain all the functionality they need. (Real life example: Flash experiments that get loaded into the presentation area)
Now imagine that Movieclip "A" uses a setInterval call to trigger a counter. This counter runs until you press the stop button which cancels the interval. (This is a simple example, so we press the start button only once, okay?) Fine. Start. Stop. On. Off. Well, this gets boring after a while so let's see what the other movies have to offer. Let's load movieclip "B" into the same _level.
Ooops, we have forgotten to cancel the interval...
Well, whatever, one interval more or less will not hurt our performance. But what's this? The counter keeps counting! It looks like the "setCounter()" function still gets called. Oh how stupid that we used the same function name as in Movie "Q". But wait a minute... In this clip setCounter should count down not up. But the numbers are going up! So this is not the new function setCounter at work, but the old one. But didn't we replace the movie on _level1 completely by loading in the new clip?
But the magic continues... Lets load Movie "C". This one is almost identical to "A" except that it counts down if you press start. Hmmm.. the counter is still counting up. I wonder what happens if I click on "Start" now? This should finally replace that evil phantom interval, shouldn't it?
Press... Oh..... The counter has stopped. Yeah! Winner! The phantom is dead! Ye... Wait. Did I say it stopped? Shouldn't it run backwards? Let's try the "Stop" button. Uaaaaa! Run for your life! The phantom 's on us! the counter goes up again. So all that happened was that we have one version of "setCounter()" counting up and another one, its zombie brother counting up.
So what to we learn? Always clear all your intervals behind you.
But one question remains: where lives that phantom function? And how can I kill it if something like that happens?Posted at September 24, 2002 11:40 AM | Further reading