Is there any sleep function in flex?

14,137

Solution 1

It always depends on what you are trying to do.

I see you are using Flex. There a neat feature in Flex that's called callLater, wich is impletemented in UIComponent. It's similar to setTimeout in use but the function will be automatically called on the next update cycle instead of a set interval of time. Suppose you set some data to a datagrid and what to select a specific cell/row in it. You'll use callLater to ensure the datagrid had time to process the data. Here's an exemple :

protected function dummy():void
{
    myComponent.callLater(myFunction, ["this is a message"])
}

protected function myFunction(message:String):void
{
    Alert.show(message);
}

If you just want to delay an execution one time, setTimeout is the way to go. If you want to execute something more than once at defined intervals, use Timer indeed.

If it's to react to some action, like a remote save function, I suggest you use events instead and listen for something like a SAVE_COMPLETE event.

Solution 2

There is no sleep function in ActionScript. Everything runs in one thread, so it would also block all user interface interactions, which is commonly perceived as a bad way to go.

The closest option is to use the Timer class which would only be started in the function in question and "fire" the code you wanted to wait after it completes it's 2 second wait.

in function:

private function whereWeStartTimer():void{
    //misc code that you always execute before starting your timer

    var timer:Timer = new Timer(2000); // 2 second wait
    timer.addEventListener(TimerEvent.TIMER,functionTimerFlagged);
    timer.start();
}

private function functionTimerFlagged(event:TimerEvent):void{
    var targetTimer:Timer = event.target as Timer;
    targetTimer.removeEventListener(TimerEvent.TIMER,functionTimerFlagged);
    targetTimer.stop();

    //put your code here that you wanted to execute after two seconds

    //force-ably destroy timer to ensure garbage collection(optional)
    targetTimer = null;
}
Share:
14,137
Rahul
Author by

Rahul

I am a AWS certified solution architect, Node.js developer and a Machine learning enthusiast.

Updated on June 04, 2022

Comments

  • Rahul
    Rahul about 2 years

    I want my code to wait for a couple of seconds before executing. So is there any function similar to sleep in flex?