Search code examples
actionscript-3flashactionscript

Infinite Loops (Action Script 3)


I'm new to Flash Actionscript because my programming class uses it. I normally use C++ (or a variant of it) and have dabbled in Java, so Actionscript was mostly familiar to me.

However, whenever I use a while loop, AS3 crashes after 15 seconds. I need to use a while loop otherwise the scope of the entire code will end and the game will stop running on code I presume. In my normal programming language, while (true) will hang the game unless I have Waitframe(); somewhere in the code to let it progress a frame. But I search, and Actionscript has no such thing, and all I've found are "Infinite loops are the devil aaaaaaaa".

Soooo, how am I supposed to be able to make a game with this? I want my game to last more than 15 seconds, yet AS3 "helpfully" terminates the script should it "hang", despite me doing stuff (although that stuff doesn't really show up at all, presumably because the script hangs). Did I miss a wait function that allows for prolonged while loop usage, or am I doing it wrong?


Solution

  • Flash works on a "Frame" system, essentially a timer by frame rate. Put all your game code in a new function and call that function using an event listener.

    stage.addEventListener(Event.ENTER_FRAME, function(e:Event):void {
      // Your code here
      // Called every frame
    });