Monday, August 31, 2009

AS3: Creating a timer event for delay/sleep

There is no sleep() method in AS3, so one cannot do:

some code;
sleep(); // Delay for x amount of time
some more code;

So one needs to use the timer class to achieve delays and such, which means that if you come from a multi thread background and are accustomed to putting in a sleep(), you would have to rethink your approach.

The timer usage is simple enough:

import flash.events.TimerEvent;
import flash.utils.Timer;

// Create the timer, generate a tick every 500 millisec, Timer ends after 2 seconds.
var new_timer:Timer = new Timer(500, 2);

// function on_tick() will be called every 500 millisec
new_timer.addEventListener(TimerEvent.TIMER, on_tick);
// function timer_complete will be called once the timer expires, 2 secs in this case
new_timer.addEventListener(TimerEvent.TIMER_COMPLETE, timer_complete);
// Start the timer
new_timer.start();

function on_tick(event:TimerEvent):void {
// some code
}

function timer_complete(event:TimerEvent):void {
// some code
}

Note the parameters, event:TimerEvent in the functions on_tick and timer_complete, those are needed else the implementation will not work.

7 comments:

  1. Thanks. It was clear, useful and it worked!

    ReplyDelete
  2. Thank you for your code. I was really puzzled with my old code but this one solved all the mystery.
    LukasT.
    atrexstudio.com

    ReplyDelete
  3. Although I found the same error with this code as with my old one. After the page is delayed in my case its 35 sec. and it goes to frme2 after another 35 seconds it goes to frame 2. Even if I'm in frame 3 after 35 sec it goes to frame 2.
    atrexstudio.com

    ReplyDelete
  4. Hi Lukas. I only use the command line compiler and no Adobe IDE. I code purely in AS3 and don't deal with a timeline.

    So I would not deal with the scenario you described. Sorry that I can't help you.

    ReplyDelete