views:

693

answers:

3

Is there any way to halt execution in ActionScript, such as a sleep() method?

I know that there is a setTimeout() method, but setTimeout() just sets up an event for deferred execution.

A: 

No. There is no sleep. Sorry.

See my answer here for options: http://stackoverflow.com/questions/1347789/actionscript-pushing-a-closure-onto-the-event-stack/1350335#1350335. It doesn't talk about sleeping, but I tried to provide an overview of deferred function calling.

Glenn
A: 

There's no way to pause all execution of an application as in PHP, but there are workarounds (unless you set a breakpoint or create a runtime error on purpose, don't think that's what you meant). Probably this is because usually flash applications are meant to execute all the scripts in less than one "frame".

It's common to be able to "pause" the animations of a website when the user unfocus it. This can be made by listening to Event.DEACTIVATE and then remove the ENTER_FRAME listeners and kill all ongoing processes.

You could also create a central EventDispatcher to replace the internal ENTER_FRAME, this way you seamlessly control speed of execution as well as pausing / resuming (won't stop executing scripts, nor asynchronous handlers such as loaders etc. though).

Theo.T
There's a hack :) See my answer.
A: 

Yes, there is, though be aware of the 15 second script timeout. ( You can change that 15 second script timeout in the Publish Settings... )

I've found in the past that if you're looking for this functionality, you're doing something wrong :)

Whatever you're trying to accomplish is probably calling for an Event listener instead.

//adding this ENTER_FRAME event listener just to show that the script pauses for one
// second before the first frame executes
addEventListener( Event.ENTER_FRAME, onFrame );

function onFrame( event:Event ):void {

    trace( "first frame occurs after pause of", getTimer() + " ms" );
    removeEventListener( Event.ENTER_FRAME, onFrame );

};

var startTime:int = getTimer();
var pauseTime:int = 1000;

while( ( getTimer() - startTime ) < pauseTime ) {
    //do nothing... we're effectively pausing here...
}
Ouch... That hurts...
Luke
Ha yeah indeed, but quite intense ...
Theo.T
This is not a sleep. You'll hit 100% CPU in the while loop. This is actually much worse than having a setTimeout call set to 1000. The only difference is that here, because of the CPU usage, you are effectively locking the program from executing any other "threads".
Glenn