PDA

View Full Version : AS3, breaking out of a function.


madcat
01-30-2009, 03:39 PM
I figure this is something simple and basic so I posted here.

If I want to break out of a function rather than a loop, it's suggested that I use the return; statement. But that doesn't work in the following code, I just want the trace statement to run once...


stage.addEventListener(Event.ENTER_FRAME, EnterFrameHandler);

function EnterFrameHandler(event:Event):void {
trace("It worked, obviously.");
return;
}


So, this will trace the phrase over and over with no stopping point. Why doesn't return have an effect?

...doesn't the first line only happen once... ?

endergrl
01-30-2009, 06:19 PM
return stops the function, but your listener is occurring on every frame, so it keeps calling the function over and over again. this is why it keeps doing the trace. if you want it to stop after doing it once just remove the listener inside the function


stage.addEventListener(Event.ENTER_FRAME, EnterFrameHandler);

function EnterFrameHandler(event:Event):void {
trace("It worked, obviously.");
stage.removeEventListener(Event.ENTER_FRAME, EnterFrameHandler);
}

madcat
01-30-2009, 06:33 PM
I see! Perfect.