How to Pause a Timeline (AS3)

Flash ActionScript 3.0

If the title of this blog entry sounds familiar, it may be because you saw the ActionScript 2.0 equivalent on this site over a year ago.  In the comments to that article, a reader named Eric asked how to pause a timeline in ActionScript 3.0 (very different from AS2, as it turns out).  There’s a significant benefit to using ActionScript (whatever version) to temporarily halt the timeline, then resume after a few seconds:  it’s all about saving yourself the hassle of horizontal scrolling.  Consider pausing for five whole minutes.  At the default 12fps, that would require 3,600 frames of timeline real estate.  With code, you can pull it off in a single frame.  Let’s take a look. 

An answer short and sweet

Create a script layer, if you haven’t already.  (It’s not strictly a requirement to put ActionScript into a layer named “scripts,” “actions,” or the like, but it sure makes locating your code much quicker in cases where the FLA has dozens of layers.)  Wherever you’d like the timeline to pause, add a keyframe to your script layer and type the following (remember, this is ActionScript 3.0) …

stop();
var timer:Timer = new Timer(2000, 1);
timer.addEventListener(
  TimerEvent.TIMER,
  function(evt:TimerEvent):void {
    play();
  }
);
timer.start();

How it works

The first line, stop(), simply stops the timeline.  If you’d like, you may use the this property as a reference to the timeline you’re in — e.g. this.stop(); — but the reference is assumed in this context, and the reference points to the MovieClip instance in which the code appears (timelines are movie clips).  In AS2, there was a global function stop() that was essentially the same thing as the MovieClip.stop() method, and you distinguished between the two by preceding stop() with a movie clip reference or not (myClip.stop(), this.stop(), etc.).  In AS3, the function simply doesn’t exist, so you’re always using the MovieClip method.

Next, an arbitrarily named variable, timer, is declared and set to an instance of AS3’s new Timer class (because ActionScript is case sensitive since Flash Player 7, the instance name timer and the class name Timer are considered two different terms).  Timer allows you to delay or repeatedly trigger a function of your choosing at a specified time interval.  Two parameters are fed into the constructor:  a) 2000, which means two thousand milliseconds (2 seconds), and b) 1, which tells the Timer instance how often to trigger the desired function.  This is a change in the way setInterval() works in AS2.  The setInterval() function triggers its assigned function repeatedly until asked to stop.  A do-it-once scenario means you’ve either got to use clearInterval() to stop the triggered function after one go, or use the setTimeout() function instead of setInterval().  The Timer class combines the best of both worlds:  specify 1 to trigger something once, 0 to trigger something forever (until told to stop), and any other number to trigger a function that many times.

Next, an event handler assigns a function to the timer variable in the manner of practically all event handling in AS3:  obj.addEventListener(event, function).  In this case, the event to listen for is TimerEvent.TIMER, and the function is a function literal in the following form:

function(evt:TimerEvent):void {
  play();
}

… which neatly starts the timeline again.

Finally the Timer instance, timer, must be kicked into gear:  timer.start().

If you want to pause for three seconds, substitute 2000 with 3000.  Six and a half seconds would be 6500; and so on.

A note about variables in ActionScript 3.0

In the AS2 version of this code, a variable named interval is declared via the var keyword, much like timer is declared here.  In AS2, you may copy/paste that version into as many keyframes as you like.  Each new time the playhead sees var, it simply creates a new variable by whatever name was specified (e.g. interval), and the existing instance of that variable is overwritten.  In AS3, things are different.  Variables may only be declared once per timeline (once per object), so if you want to pause your timeline at more than one keyframe, you’ll have to leave off the var declaration in all cases after the first one:

// First keyframe used …
stop();

var timer:Timer = new Timer(2000, 1);
timer.addEventListener(
  TimerEvent.TIMER,
  function(evt:TimerEvent):void {
    play();
  }
);
timer.start();

// Any keyframe after the first time used …

stop();

timer = new Timer(2000, 1);
timer.addEventListener(
  TimerEvent.TIMER,
  function(evt:TimerEvent):void {
    play();
  }
);
timer.start();

32 Responses to “How to Pause a Timeline (AS3)”

  1. io Says:

    Posted this in the other article:

    setTimeout(); works for me in AS3, but not setInterval();

    stop();
    setTimeout(function () { play();}, 2000)

    If you’re just going for a simple two-second pause on the timeline.

  2. David Stiller Says:

    io,

    Ah, I saw your similar comment in the AS2 version of this article. For convenience, I’ll post the same reply here, as it applies in this case, too:

    Although the setTimeout() and setInterval() functions are still available in ActionScript 3.0, they’ve been re-routed to the flash.utils package; in addition, the ActionScript 3.0 Language Reference strongly recommends the Timer class instead: “Although you can use this method, it will generate a compiler warning. Instead of using the setInterval() method, consider creating a Timer object, with the specified interval, using 0 as the repeatCount parameter (which sets the timer to repeat indefinitely).” source

  3. Brice Lucas Says:

    David I just bookmarked your blog. This article was professionally executed and was extremely easy to follow, a rarity these days. I am going to use this script on a current project www.warriorepic.com. Check it out if you would like, the site has only been live for a few days and I have yet to implement any flash on it.

    Peace
    Brice

  4. David Stiller Says:

    Brice,

    Thanks!

  5. Chris Ellem Says:

    Thanks David,

    This code works a treat in Flex…..
    Just replace the play(); function with the function you want to call..

  6. David Stiller Says:

    Chris,

    You bet. :) The Flex framework is written in ActionScript 3.0, so standard AS3 classes, such as Timer are usable in both worlds.

  7. Jeff Says:

    I may be a little off topic, but I’ve been searching for a way of doing this without any luck and would like to see if anyone else has encountered the same — In AS2 I would use setInterval and pass in a reference to the needed movieclip so that it can be found when the interval is complete. Using AS3 with the Timer object I haven’t found a way of referencing the needed movieclip once the timer event has been called. Anyone know a good way of doing this?

  8. David Stiller Says:

    Jeff,

    The reference needed in AS2 was a (potentially) frustrating result of the way scoping works in that version of of the language. In AS3, your Timer event handler can reference the desired movie clip in the same way it would if that code were simply sitting on the timeline (rather than inside an event handler). Much easier!

  9. martoon Says:

    let me preface this with, “I’m not much of a coder”, I’ve tried implimenting the code but get the following errors
    The class or interface ‘Timer’ could not be loaded.

  10. David Stiller Says:

    martoon,

    It sounds like your document is configured for ActionScript 2.0, and the approach shown above is for ActionScript 3.0. If you’re using Flash CS3, you can go to File > Publish Settings > Flash tab and choose 3.0. If you’re in an earlier version of Flash, use the 2.0 approach.

  11. martoon Says:

    Great, that solved it. Thanks!

  12. Gary Says:

    By using the packages and using your favorite text editor do you need to put anything on the stage in flash, when using AS 3.0?
    just a question

    [Note: This comment seems to refer to another topic, as the article about pausing the timeline doesn’t need classes or packages.]

  13. David Stiller Says:

    Gary,

    If you use Flash CS3’s Document class field in the Property inspector, you can associate your FLA with any AS3 class definition you like, as long as that class extends either Sprite or MovieClip, as appropriate. You could, in fact, put absolutely nothing on the Stage.

  14. Gary Says:

    I typed it using notepad then copied over to flash to see if there were any errors and these are the ones i found

    I have another 2 errors that i cant seem to find a solution for on the web.

    error 1 is 1084: syntax error: expecting rightparen before colon.
    here is the code
    _stage.addEventListener(MouseEvent:MOUSE_MOVE, draw);

    error 2 is 1013: theprivate attribute may be used on on class property definations
    here is the code
    private function dispatchColorPicked (mouseEvent:MouseEvent):void

  15. David Stiller Says:

    Gary,

    I just realized we’ve been jumping around a bit on these blog comments. No harm done, but this particular entry (pausing the timeline) doesn’t make use of classes or packages, so I’m mentioning that in case the topic confuses other readers.

    Your first error may be due to your _stage reference (not sure). By the looks of it, your parentheses are certainly in the right place. Unfortunately, these messages sometimes get confused about what line is the cause of an error. Your summary of error 1013 seems to have a few typos, so I’m not sure what’s going on. It certainly is possible to use private on a class member, such as a method or property, but only if that member is used inside the class only.

  16. Shelly Colvin Says:

    I am creating a animation nested inside a movie clip and I have two buttons on the stage.
    button one is the pause button
    I would like to pause the movie clip or everything on the stage when this button is pressed.
    button two is the play button
    I want everything to resume playing when this button is pressed.

    I know how to do this in AS2 but not in AS3. I have the basic button code but I can’t get pause():void or resume():void to work. Do you have any suggestions?

  17. David Stiller Says:

    Shelly,

    The timelines of movie clips run independently from the timelines in which those movie clips reside. If you stop the main timeline, for example, a movie clip inside that timeline will continue to play — and it sounds like you already understand that part. :)

    To pause both the main timeline and a given movie clip symbol, you’ll have to invoke MovieClip.stop() on both those entities. The movie clip will need an instance name, of course, and it sounds like you don’t need a Timer instance in this case. So it might go something like this:

    pauseButton.addEventListener(MouseEvent.CLICK, pauseTimelines);
    playButton.addEventListener(MouseEvent.CLICK, playTimelines);
    
    function pauseTimelines(evt:MouseEvent):void {
      stop();
      otherMovieClip.stop();
    }
    function playTimelines(evt:MouseEvent):void {
      play();
      otherMovieClip.play();
    }
  18. Shelly Colvin Says:

    Thank you! perfect! You’re so awesome! Here is what I made just testing the script and playing around trying to learn AS3. I know its nothing special but it works and thats all that matters! :)

  19. David Stiller Says:

    Shelly,

    Fantastic! Glad to hear it.

  20. Hunka Says:

    i read your tutorial and found it is quite useful, i hope it works fine on my project.

    regards,

  21. David Stiller Says:

    Hunka,

    Thanks!

  22. Steve Says:

    David,
    Using AS3. I had no problem creating an instance of the timer class - it works fine. My problem is this - how do I get the timer to start upon the occurrence of a MOUSE_UP event??

    MOUSE_UP event now gets a new URL for my button instance, but I want to delay the GetURL function for 2000ms to play the remaining animation that’s already playing as a result of MOUSE_DOWN.

    Steve

  23. David Stiller Says:

    Steve,

    Assuming a button with the instance name myButton, you could do this:

    stop();
    
    var timer:Timer = new Timer(2000, 1);
    timer.addEventListener(
      TimerEvent.TIMER,
      function(evt:TimerEvent):void {
        navigateToURL(new URLRequest("http://www.domain.com/"));
      }
    );
    
    myButton.addEventListener(
      MouseEvent.MOUSE_UP,
      function(evt:MouseEvent):void {
        timer.start();
      }
    );

    This example is very close to what’s shown in the original article, only the start() method is called inside the MOUSE_UP handler. (Note that the AS3 version of getURL() is navigateToURL(), which requires an instance of the URLRequest class, rather than just a string).

  24. Jeremiah Says:

    Hey I was hoping someone could help me out. I’m trying to build a custom flv player with a scrub bar, in action3.0, I’ve been using Lee’s tuts to build in 2.j0 and converting to 3.0 the only thing I can’t figure out is the scrubber part. Is there a tut out there done in 3.0

    Thanks

    J.

  25. David Stiller Says:

    Jeremiah,

    This particular blog entry is about pausing movie clip timelines, but I do have a related tutorial on this blog for an AS2 scrubber for FLVs. I do plan to update it to AS3 sooner or later, but for the time being, at least, it may give you ideas on how to proceed in your conversion.

    How to Build a Flash Video (FLV) Progress Bar (Part 2)

  26. Sensi Says:

    Thank you David for that commented example, having not done any flash for nearly ten years you have almost saved my life. ;)

  27. David Stiller Says:

    Sensi,

    Glad to help!

  28. Rick Gutierrez Says:

    Thanks David! This tutorial was exactly what I was looking for. This was much easier to understand for me than the olds AS2 way of doing things.

    Thanks Again,
    Rick

  29. James McLean Says:

    Just wanted to say THANK YOU! I’ve just spent hours trawling through information about the timer class but nothing was using it in the way I wanted and then I came across this page. PERFECT

  30. David Stiller Says:

    To Rick …

    Glad to hear it!

    To James …

    You’re welcome. :)

  31. brian p Says:

    finally i’ve fond someone who explains all this code without me wanting to headbutt the screen in frustration. many thanks david !
    now fr my stupid question ….
    the ‘1′ which tells the timer how many times to pause….i tried this but my flash movie keeps pausing it forever, ie each time the timer comes to the frame.
    am i doing something wrong or just being thick ?

  32. David Stiller Says:

    brian,

    Aha! I see what you’re thinking (I think!). Nah, you’re not being thick … you’re just interpreting the concept of “trigger this function once” in a different way.

    When the playhead enters the frame in which this code appears — and this is true of any and every time the playhead enters this frame — Flash obeys the instructions and performs timer.start();, which means the event handler associated with the timer instance is going to do its thing … once.

    If you were to replace that 1 with a 2, the TimerEvent.TIMER handler would perform its duties twice (following two 2-second delays). If 3, then thrice (following three 2-second delays). 0 repeats forever.

    Does that nail it?

Leave a Reply