Blog

  • Calling Functions Repeatedly in ActionScript 2 & 3: setInterval, setTimeout, and Timer

    Pre-ActionScript 3, Flash could use setInterval. This method allows you to have a function called at a recurring time frame. So, you could have a “hello” function called ever 3 seconds.

    setInterval(hello, 3 * 1000);
    setInterval(someScope, "hello", 3 * 1000);

    Both forms invoke the function “hello” every 3 seconds. I personally always used the 2nd form to avoid any weird scope issues and EXTREMELY easier to debug; there is no confusion over what scope the function is being invoked in.

    You can stop the interval from calling your function over and over by clearing it. All intervals created return ID’s, which are a unique number identifying the interval. If you want to clear an interval, you have to keep the number around to clear it later. This number is returned when you call setInterval.

    theID = setInterval(this, "hello", 3 * 1000);
    clearInterval(theID);

    Intervals are dangerous. If you forget to clear one, it can continue running in the background, leading to memory leaks and performance issues. Since there is no visual indication for intervals that do not call GUI related functions, and the API for them is small, they are hard to track down.

    The 2 main ways to ensure in ActionScript 2 that you never have problems is to always call clearInterval right before you call setInterval with the same ID, or use Kenny’s interval management class.

    Flash Player 8 introduced the setTimeout function. Most uses of setInterval were really for delaying the calling of functions. Because Flash is all about events, and programming in it is very asyncronous in nature, one tends to adopt the calling of functions in a similair fashion; you wait for other things to happen before you yourself call functions rather than immediately. Such as waiting for the screen to refresh, giving a CPU intensive operation additional time to cool down, or launching a hyperlink when your content is loaded. There are some issues in using it in a class, and it was mysteriously not documented, but Guy has some good info on it’s usage in the comments. You can also clear a timeout just like clearInterval via clearTimeout.

    As of Flash Player 8.5, and thus ActionScript 3, setTimeout is relegated to being depreciated already. Damn… that function only lasted HALF a player version. That’s a first.

    Both setInterval & setTimeout were moved to the flash.util.* package.

    The new class to use for both use cases, repeatedly called functions and post-poned one shots, is the Timer class, also defined in the flash.util package. Both intervals and timeouts tended to pollute your class in their usage, more so intervals than timeouts. You usually had to not only keep a property that held your interval id, but also all the management code for making sure the interval was cleared, mixing both the function that’s run and the interval management in one.

    Now that Timer is it’s own class, this is a lot cleaner. On the flip-side, it knows nothing of your code, however, so it’s up to you to call the function, which actually adds more de-coupling; you can choose to call the function or not, and still let the timer continue running. Or, you can just do it the old fashioned way, and have the listener function BE the function you want called.

    One thing I don’t really like about it however is its name; it’s not really a Timer in the general sense of the word because it isn’t timing anything, at least that it exposes to you. Rather, it’s more of a beacon, and fires off just 1 event, “timer”. Granted, you could use the Timer class to create a timer.

    Here’s a code snippet example from the docs commented:

    // create a timer with a 1 second
    // delay, that fires twice
    var myTimer:Timer = new Timer(1000, 2);
    // have your onTimer function listen
    // for the timer event
    myTimer.addEventListener("timer", onTimer);
    // unlike an interval & timeout,
    // she doesn't start ticking
    // until you start it
    myTimer.start();
    // this function will run twice,
    // every second,
    // starting 1 second after you call start
    function onTimer(event:TimerEvent)
    {
            trace("onTimer: " + event);
    }
    

    The 2nd parameter to Timer, and also a public property, is the repeat count. This allows finer grained control on how many times the timer event is generated. You can set it to 1, 20, or 4,294,967,295 times… which would take 7 weeks assuming your function took 0 milliseconds to run.

    What’s special about it, though, is 2 things. First, you can set it to 0, which is infinity. Basically, it’ll keep going until you stop it.

    Second, it’s a public, writable property. Meaning, you can change the speed it goes WHILE it’s going, or while it’s stopped.

    This goes for the delay as well. It, too, is a public property that you can change, speeding up or slowing down the running timer.

    Frankly, I don’t think setTimeout is deprecated as they say it is. It feels a lot more elegant to me to just use 1 function to make an intentionally prolonged function call. Still, Timer is a, if not aptly named, pretty bad ass new class.

  • Bluetooth Wireless Keyboard for my Nokia 6680 Phone


    My Nokia Bluetooth Wireless Keyboard arrived today for my Nokia 6680 cell phone. Retails for $199, but I got it for about $139 at Mobile City Online. It’s only fitting that I get a keyboard for a phone that boots. There is definately a line a device crosses, more so a phone when the words “boot” and “shutdown” enter your vocabulary when describing its functions as opposed to “on” and “off”.

    While wireless itself isn’t new, the fact I can blog from my dining room via tools that fit in both pockets is just wicked. All I need to do is make a lighter weight interface in HTML since the current MoveableType one is too heavy for this phone’s browser…at least, I think it is. I can already email my pictures to Flickr, so once I get cellblogging on this mofo, I’m set!

    The last trip I took, I didn’t have a laptop, just my Nokia 3300 which had text & multimedia messaging which doubled surprisingly well as email. Flickr worked the same, although the camera wasn’t near as good.

    Now, I can check real email as this one suppports POP and IMAP; she’s slow, though, because I usually get like 200 emails an hour, and the phone’s MEdia net connection certainly isn’t broadband.

    :: back on computer ::

    MAN, my next keyboard will definately be an ergo… geez, I certainly couldn’t make my living coding on that mofo in a coffee shop.

  • AS3 Chronicles #3: Enter Frame Event & _root Class

    You can finally add event listeners to MovieClip events. Whats more, you can register for the enterFrame event and you don’t have to have something “visual” to do it. You just create a new MovieClip or Sprite in your class, register for the event, and never add it to the Display List. In the example below, I just create a MovieClip, register for it’s enterFrame event, and pass in the function to call.

    package
    {
            import flash.util.trace;
            import flash.display.MovieClip;
            import flash.events.EventType;
            import flash.events.Event;
            
            public class EnterFrameTest extends MovieClip
            {
                    // define our movieclip
                    private var nonVisual_mc:MovieClip;
                    
                    // this main function gets executed when our SWF is run
                    public function EnterFrameTest()
                    {
                            nonVisual_mc = new MovieClip();
                            // register for the enter frame event; no Delegate, yay!
                            nonVisual_mc.addEventListener(EventType.ENTER_FRAME, onEnterFrame);
                    }
                    
                    // event handler function, runs every enter frame
                    private function onEnterFrame(event:Event):Void
                    {
                            trace("enter frame");
                    }
                    
            }
    }
    
    

    That’s it!

    You’ll notice there is a constructor function that is public. Like all constructors of classes, they are run when a class is created. The cool thing about this class is that it is a “main” class. Main classes are the top level class of ActionScript projects. When you compile an ActionScript Project, as opposed to a Flex Project, it uses that class as the main class, or “_root” as it were, in this case “root”, since underscores have been removed from ActionScript to clean up the API, namely in the MovieClip arena.

    So, if you trace out root in your main function:

    trace("root: " + root);

    She’ll show “root: [object EnterFrameTest]” in the Console Window since this is your main class, and thus the true root of the SWF. To get the effect in AS2, you’d merely override _root’s __proto__ property on frame 1 of your Flash SWF, like so:

    import com.jxl.controller.Application;
    // do this to ensure class is exported
    var depend = com.jxl.controller.Application;
    delete depend;
    
    this.__proto__ = _global.com.jxl.controller.Application.prototype;
    
    _global.com.jxl.controller.Application.apply(this, null);// call constructor
    
    if(this.loaded == false)
    {
            this.onLoad(); // have to call onLoad manually
    }
    

    Flex does something similiar with it’s Application class.

    The cool thing here is we finally have a class associated for the _root of our SWF’s, and the base class only has to be Sprite. You could use MovieClip if you wanted (I do in the example above, but always use Sprite when I can). You cannot use Bitmap, since although Bitmap does extend the DisplayObject, he is not a sub-class of Sprite. What this means is, you could create your own “MainClass”, that extends Sprite, and make that your main application class. Cool stuff!

  • Winter: Fireworks MX 2004 Painting

    Hit a snag last night trying to figure out why my BitmapData was getting cropped when I was sure my Bitmap was not using a scrollRect. If you don’t know what that means, neither did I at 10:00pm… I just gave up, and went to change my website banner. I wanted to do something Fall related, but… to me, Spring and Fall are just transitory seasons, used to emotionally delay the inevitable, so I went straight for winter.

    To me, winter no matter where you are, is harsh and unforgiving. I have a love hate relationship with winter. While I loathe cold, I at the same time feel most alive in freezing weather. I really dislike feeling chilly at all, but being able to deal with such weather certainly makes me feel more awake, aware, and attuned to my surroundings.

    I took inspiration from the Silver Marches, a harsh, northern frontier region in nothern Faerun of the Forgotten Realms. To me, that place exemplifies the harshness of people living in the cold of winter. Danger is everywhere, and yet even eeking out a meager living itself is immensely challenging and continues to be every day.

    I used the light water color brush with varying weights, as well as thick and heavy brushes for the mountain and moon. I used colored pencil for more detailed areas. I’ve always liked artwork that incorporated water color and colored pencil combined. I think the coolest medium I ever was turned onto was water color pencils by an art teacher in my high school art class. You can draw with them, and then just stroke a wet brush over them, and they turn into water color. It’s awesome. I utilized my Wacom tablet with pen to paint, an Intuos 2 Platnium 9×12.

    Although I own Fireworks 8 via Studio 8, Macromedia did something that I consider really stupid. When selecting a brush type, you can preview it’s painting effect in these wonderful popups that show the brush with your current color selection.

    For some reason, in 8, you have to actually hover over the brush name itself whereas in MX 2004, you can just hover over the group, and it’ll preview all brushes for that group.

    I reckon users who complained where running Fireworks MX 2004 on Pentium 2’s, but I don’t see why I must be punished because I have a fast machine. Sounds like taxing the rich just because they are rich. Stupid.

    Anyway, in college, I would of chosen Painter to do something like this, but Fireworks certainly has matured from the “alpha channel PNG maker” that I used it for back in college.

    Winter by JXL – Source PNG & JPG

    BTW, if you marquee select the 3rd bitmap in the sky layer (Control + Click in MX 2004, Alt + Click in 8), you can make the stars twinkle.