How to Pause a Timeline (AS2)

Flash ActionScript 2.0

Note:  An ActionScript 3.0 version of this article is located in a more recent entry of this blog.

The timelines in Flash are an especially good metaphor for tween-based animation.  If your frame rate is the default 12fps, then a span of twelve frames lasts approximately one second.  If your frame rate is 24fps, that same span lasts approximately half a second.  Pretty straightforward.  It can get tedious, however, when you want your animation to pause for, say, 15 seconds before moving on.  At 24fps, you’d need 360 frames!  That’s 360 frames of perhaps a dozen layers.  Ack!  Isn’t there another way to pull off the same visual effect?  Enter, ActionScript. 

An answer, short and sweet

Add a keyframe to the position in your movie where you’d like the timeline to pause.  Any layer will do, but if you like to be organized, create a dedicated scripts layer.  Click into this keyframe and paste the following ActionScript.

stop();
var interval:Number = setInterval(
  function():Void {
    play();
    clearInterval(interval);
  },
  2000
);

How it works

The global stop() function stops the current timeline.  The global setInterval() function waits two seconds, then invokes a function literal that a) causes the current timeline to continue and b) prevents the function from repeating.

setInterval() can be used two ways.  The above approach accepts two parameters:  a function reference and a time interval in milliseconds.  The function reference can be a named function or, as above, a function literal.  It may help to step through how this was “built.”  Bullet #4 would work just fine, by the way.  Line breaks don’t really matter, so long as the punctuation is correct.

  1. setInterval(functionReference, timeInterval);
  2. setInterval(functionReference, 2000);
  3. setInterval(function():Void {}, 2000);
  4. setInterval(function():Void {play(); clearInterval(interval);}, 2000);

So, what’s this clearInterval() business?  Well, any function reference you pass to setInterval() will be invoked repeatedly.  On its own, the play() function would be issued every two seconds, nonstop, which might interfere with other stop() functions in other frames of the movie.

The purpose of the global clearInterval() function is to halt this repetition.  clearInterval() accepts one parameter, a number that identifies which interval (of perhaps many) to halt. And how would you know which number to supply?  Well, thankfully, setInterval() returns a value, which is exactly the number you need.  It’s very much like those “take a number” machines where you grab a piece of paper while waiting your turn.  In the above example, we’re storing that number in a variable, arbitrarily named interval, and using that as our parameter.

Variations

Change the 2000 to whatever you like to adjust the pause length.  This number is in milliseconds, so 15 seconds would be 15000, a minute would be 60000, five minutes would be 300000, and so on.  Half a second would be 500.

The above code works in any timeline, you may use it in the frame of any movie clip to pause that movie clip alone.

158 Responses to “How to Pause a Timeline (AS2)”

  1. Rich Says:

    stop(); my beating heart… You’re the man, Stillonius

  2. 木頭 Says:

    stop();
    setTimeout(function () { play();}, 100)
    It works OK in as2.0+!

  3. vm Says:

    what if you wanted to scope the id to a mc or object?

  4. David Stiller Says:

    木頭,

    Your setTimeout() example is an interesting one. setTimeout() is indeed a valid, “documented” global function, but you won’t find it in the ActionScript 2.0 Language Reference (at least, not at the time of this writing). It was inadvertently omitted from the Flash 8 documentation, according to notes on this page of the Flash 8 LiveDocs …

    http://livedocs.macromedia.com/flash/8/main/00001717.html

    setTimeout() works when I publish to previous SWF versions, so I’m unclear what Player is required to use it.

    vm,

    I’m not sure I understand your question. The interval variable (what you’re calling the id, I think) is scoped. It’s scoped to the timeline in which the script appears. If you scoped it elsewhere — by preceding it with a relative or absolute path — you might just put it out of sight of that clearInterval() function, in which case setInterval() would keep triggering play() for the rest of the movie. That may or may not be harmful. If you had a handful of other stop() functions strewn about the timeline, the looping play() trigger might coincidentally interfere with those.

  5. Sam Goudie Says:

    THANK YOU! I’ve wanted to know how to do that for ages. Its nice to know that there are friendly people to help out!

    Just another question, I’ve had some problems with Flash Player 8. On PCs on Internet Explorer the flash file has to be clicked on to use. Something about active X I think? How do I stop this?

  6. David Stiller Says:

    Sam, thanks! A lot of what you need out of ActionScript is easy enough, once you have your bearings.

    The Internet Explorer issue you refer to affects not only Flash 8, but all previous versions, as well as any plug-in that requires an ActiveX control, including embedded Windows Media content, QuickTime videos, and more. It’s due to a recent decision Microsoft made in regard to Active Content (of any kind) due to the result of a patent-infringement case brought against them. In other words, it’s not anything caused by Adobe and is not a Flash bug. There are quite a few workarounds. My favorite is a free JavaScript application called SWFObject, available here …

    http://blog.deconcept.com/swfobject/

    Complete details of this Microsoft issue are available here …

    http://www.macromedia.com/devnet/activecontent/

  7. jon Says:

    Hi

    I am a noob with actionscript and have tried copying and pasting the above code into a couple of frames which are spaced out on the timeline. It seems to work on the first run, apart from 1 point where it didnt pause. Then on the second run, there are some other points which fail to pause. Any idea whats wrong here?

    Thanks

    Jon

  8. David Stiller Says:

    Jon,

    I’m happy to help you if I can, but I may need more information. I just created a new FLA with ten keyframes and pasted the exact code from the original blog entry into each keyframe. Testing the SWF, I saw the timeline pause without a hitch for exactly two seconds in each one.

    What else is going on in your FLA? What happens if you try it in a FLA without anything else?

  9. jon Says:

    David,

    sorry i forgot to mention i changed the interval time to 10 seconds. I tried the code in a new simple FLA just for testing. if you keep watching the movie repeating, the interval time will gradually reduce until there is almost no pause at all.

    would the frames per second setting have any effect on the interval time? My movie that im working on is 30fps, but my test movie was 12fps anyway.

  10. David Stiller Says:

    jon,

    It makes no difference how long the pause is or what the frame rate is, which makes this particular technique pretty easy to reuse. It sounds to me like your id variables aren’t getting cleared by clearInterval(). So there must be something else going on in your FLA that’s different the original example. (You forgot to mention how you changed the interval, for example — not that that particular change hurt anything — so you may have made some other change, too. In other words, you didn’t just copy and paste.)

    Have you tried debugging your ActionScript? That might be a real eye-opener for you. Check out this entry, here and see how that helps.

  11. jon Says:

    David,

    other things that going on FLA: motion/ fade tweening, buttons, stops in main scene. i changed the interval just by changing 2000 to 10000.

    Like i said in my previous post i made a quick new FLA with just a simple tween, nothing else with the exact same code. And the same problem occurs.

    i uploaded my test FLA here if you want to have a look: http://www.angelfire.com/amiga2/dissjk/test.fla

  12. David Stiller Says:

    jon,

    Aha! Okay, here’s the thing. I looked at your publish settings, and you’re publishing for ActionScript 1.0 There’s nothing wrong with that, but it means you can’t use use the strong-typing I used in my original example. The solution for you is either a) drop the :Number suffix in line 2 of my code or b) change your publish settings to publish for ActionScript 2.0. That solves it. :)

  13. jon Says:

    David,

    I didn’t manage to find the actionscript setting in publish settings. (Im using MX version 6.0) . However I managed to fix the problem using method (a). Thanks for helping me out. :)

  14. Lucas Says:

    David,
    Thanks for the insight and bit of code to make the timeline advance. I have a project with about 30 keyframes of different images on each separate keyframe, and need to make them advance after 30 secs, and also at the end, go to another scene like a homepage. The code works fine for a few frames, then the timing seems to mess up and advance in 6 or 8 secs. I am using Flash 8, and the actionscript is 2.0…Any idea on why?
    Thanks, Lucas

  15. David Stiller Says:

    Lucas,

    If the timing goes batty after a number of frames, it’s because your interval ID — the variable I named interval above — isn’t being recognized by clearInterval(). Add trace(interval); just before the play(); function in the sample code above. See what you get in the Output panel. If it’s something other than undefined, a bunch of times, I’ll eat my hat. ;)

    In Jon’s case, it was because his FLA was made in Flash MX and was therefore restricted to AS1. You’re saying that’s not the case for you, so I’d probably have to look at your FLA file.

  16. Lucas Says:

    Hi David,
    Thanks for the suggestion…Tried the trace(interval); as suggested, but it still does the same thing… The output panel shows sequential numbering as the page changes.
    Here’s the code. Have I missed something?

    stop();
    var interval:Number = setInterval(function () {
     trace(interval);
      play();
     clearInterval(interval);
    }, 24000);

    Thanks, Lucas

  17. David Stiller Says:

    Lucas,

    Tried the trace(interval); as suggested, but it still does the same thing…

    It sure would; but trace() allows you to look under the hood, so to speak. And since your Output panel shows sequential numbering instead of undefined, I guess I have to eat my hat. ;)

    Do you have this same code — not counting trace() — on each of your 30 keyframes?

  18. Lucas Says:

    David,
    I have the same code on each of the 30 keyframes, including trace()…
    Thanks for your continued effort! It’s appreciated. Lucas

  19. David Stiller Says:

    Lucas,

    After looking at your file, I can see what’s happening. The timer only goes nuts if you click those Next and Previous buttons. If you leave those alone — which is hard to do patiently, because each frame waits 24 seconds — it all works fine.

    Here’s why it breaks when you click those buttons. Imagine you’re the playhead and you’ve just arrived on frame 1. You see some ActionScript, so you execute it:

    stop();
    var interval:Number = setInterval(function () {
      play();
      clearInterval(interval);
    }, 24000);

    First, you stop the timeline. Next, you declare a new variable, thanks to that var statement, and you set your variable to whatever value comes back from that setInterval() function. Since this is your first interval, the return value happens to be 1. Fine, that’s good and stored. setInterval() will trigger play() in 24 seconds, but you’re not worried about that yet. In addition, it will clear the interval, but again, you’re not worried about that yet. That’s 24 seconds away.

    Now, someone clicks the Next button. Ah, well, that’s fine … since the button was clicked, you have a bit more ActionScript to cater to.

    on (release) {
      gotoAndStop("Restaurants", 2);
    }

    That’s easy enough. All you have to do is go to frame 2 of the Restaurants scene and stop. Done. When you arrive at frame 2, it’s deja vu: again, you see …

    stop();
    var interval:Number = setInterval(function () {
      play();
      clearInterval(interval);
    }, 24000);

    Shoot, that’s easy; you’re familiar with this. First, you declare a fresh, new variable, interval. You set its value to whatever comes back from setInterval(). This happens to be your second interval, so 2 comes back. Etc., etc.

    Suddenly, the interval from frame 1 comes to pass. 24 seconds have elapsed, so you tap your head thoughtfully and think to yourself, “What was I supposed to do in 24 seconds? Oh yeah, play(). And then clearInterval(interval). What’s the value of interval again? Oh yes, 2.

    See what’s going on? The first interval never gets cleared. If the user happens to click one the Next or Previous button several times, this is only compounded.

    One way to solve this dilemma is to add a clearInterval() to your button code.

    on (release) {
      clearInterval(interval);
      gotoAndStop("Restaurants", 2);
    }

    Until you hit frame 2, the value of interval is still 1, so that first interval will be propertly cleared. Make sense?

  20. Lucas Says:

    David,
    On the previous example it goes from frame to frame…How would you tell it to go to a different scene altogether? I tried inserting a gotoandPlay at the end of the code, but it seems to negate the timer part totally. Thanks, Lucas

  21. David Stiller Says:

    Lucas,

    You have discovered one of the reasons why Scenes are deemed “evil” by a number of developers. Scenes don’t play particularly well with ActionScript, in spite of claims to the contrary in the gotoAndPlay() and gotoAndStop() function entries of the ActionScript 2.0 Language Reference.

    Scenes are nothing more than an organizational convenience in the authoring environment. During the publishing process, all Scenes are actually collapsed into a single timeline in the compiled SWF. Because each timeline can have its own arrangement and number of layers, these collapsed timelines don’t always match up. I wish I knew more about the technical reasons for this, but suffice it to say that Scenes can add an element of voodoo to otherwise clear circumstances.

    The recommendation I see most often in the Adobe forums is to forego Scenes when using ActionScript. Instead, put all assets in a single timeline and use frame labels, as necessary, to distinguish “scenes.”

  22. kevin williams Says:

    David

    Have just put together a linear movie which contains audio. The whole thing probably lasts 7-8 minutes.

    The audio has now been changed approximately 5 minutes into the linear movie, which means anything after 5 minutes is now slightly out of sync.

    Is there a way to pause the audio layer only, and let the other layers run as normal.

    Thanks. Kevin

  23. David Stiller Says:

    Kevin,

    For the most part, a timeline is a timeline — and everything in it is “locked in” with everything else, even on separate layers. I say “for the most part” because audio and video are a bit different. Audio, for example, has a number of Sync choices in the Property inspector. Select the keyframe that holds your audio and you’ll see what I mean. The important ones are Event and Stream. Event means that an audio file, when referenced in a timeline, is loaded into memory in entirety and played in entirety unless purposefully stopped. Stream means that the audio is locked in step with the timeline, which makes this a favorite approach for tight synchronization, such as when a cartoon character’s mouth “speaks” words in the audio. Steam also lets you scrub the timeline and actually hear the audio in context.

    I mention this because your SWF may seem synchronized to you, on your equipment with your processor and RAM, but it may already be out of synch on someone else’s computer — even without the recent edit — if you’re using Event. Just something to bear in mind.

    As for the recent edit, I would suggest you split the audio into two separate files (split them at the point where you wish you could pause the sound). Place the second half at the appropriate place in the timeline.

  24. stedben Says:

    Mr Stiller, I have been looking through website after website for someone who could explain setInterval() in human language. After visiting several forum and tutorial sites, I found your blog…

    Please let me say that you have a gift for teaching and I am glad to be your student. I look forward to learning from the rest of your tutorials.

    MANY thanks.

  25. David Stiller Says:

    stedben,

    Wow, thanks! I’m glad to hear my explanation makes sense to you. I hope you get as much out of the rest of the site.

  26. SiiKDave Says:

    Hi David,

    Thank you for a fantastic and simple solution. I had been using the example I’ve included below, but was causing problems when publishing to earlier player versions, I believe caused by the onEnterFrame.

    So again, Thanks!

    SD

    stop();
    var interval:Number = 2;
    var startTime:Number = getTimer();
    this.onEnterFrame = function() {
    var currentTime:Number = getTimer();
    if (currentTime>=startTime+(interval*1000)) {
    delete this.onEnterFrame;
    gotoandplay(66);
    }
    };

  27. David Stiller Says:

    SiiKDave,

    The ActionScript 2.0 Language Reference states, for each entry, the first version of the Flash Player to support that feature. Depending how far back you go, it may indeed have been the MovieClip.onEnterFrame event — in Flash 5, you would have had to use onClipEvent(enterFrame) — but it might also have been the strong typing (:Number), which is only available to ActionScript 2.0.

  28. Travis Swinton Says:

    hey man you still got the skills. Stilla in Manilla

  29. Karen Diane Says:

    I’ve searched the web for a script that is easy to understand and that works.

    Thanks for keeping it simple.

    Regards,

  30. David Stiller Says:

    Sure thing, Karen! Glad to help.

  31. Jake Says:

    This script is great, but I have a problem that maybe from my inexperience with Flash in general. In my timeline, I have scripts that go to different parts for different content. When a user clicks CLOSE then it takes them back to one of the first frames in the timeline. When I use this script it works great, but when it goes back to where the (CLOSE) function tells it to go, it then continues to the next Stop(); and waits for the alloted time in the script before continuing throughout the entire movie. Did I do something wrong or is there something I can do about this?

    Thanks

  32. David Stiller Says:

    Jake,

    I sounds like your clearInterval() isn’t managing to close the setInterval() loop, but I’m not 100% sure I understand the problem you described. If there’s a “close” button that essentially overrides the timeline pause, then you need to make sure your button also uses clearInterval(), along with id, or whatever variable you’re using to capture the return value of setInterval(), to keep the play() action from occurring.

  33. Andy Thelwell Says:

    Hi,

    I can add to the debate about the problem with this function.

    The following set of circumstances can cause serious problems (movie restarts or acts oddly)…

    1) An MC (lets call it my_mc) exists on stage
    2) Implement the above setInterval function within my_mc to add a pause to its timeline
    3) The user clicks (or something else) to take them somewhere else in the movie, where my_mc no longer exists
    4) when the interval is called, the “play()” command now doesn’t know what it is referring to and the _root timeline will restart/play instead

    Regards,

    Andy

  34. David Stiller Says:

    Andy,

    Careful pathing will take care of that for you. Rather than using the global play() function, use its cousin MovieClip.play() method, instead. The only gotcha is that the global this property won’t refer to the desired movie clip’s timeline without extra help, such as the Delegate class available since the Flash MX 2004 7.2 minor revision.

    import mx.utils.Delegate;
    this.stop();
    var interval:Number = setInterval(Delegate.create(
      this, function () {
        trace(this);
        this.play();
        clearInterval(interval);
      }
    ), 2000);
  35. craig Says:

    Can you use the initial script more than once. It seems like if you do the amoutn of time can not be changed? Am I missing something..I’m sure I am. Thanks

  36. David Stiller Says:

    craig,

    Whenever you want a frame to pause, copy/paste the script in place. Adjust the number part (2000 in the original example) as desired for that frame.

  37. Bob Burwell Says:

    Thanks very much for the Pause script. I’m only a newbie and yours is the simplest I’ve found.

  38. Paula Lynch Says:

    Mr. Stiller!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    I feel like I owe you my life!! I have searched for at least 2 months on the internet to find this! Thank God I finally ended up here! Oh my goodness I am so elated you cannot know!

    I have tried sooooooooooo many scripts and none worked. I am doing a flash intro for someone’s site & in between phrases that slide in I needed a 5 second pause.

    You could have knocked me over when I thought “ok, let me try Mr. Stiller’s instructions” and it worked! I was so used to seeing the intro go on as usual I just could not believe my eyes! The only thing I had to change, when I clicked “Script Assist” it told me I had to publish in Flash 5. I changed that - the only thing I had to do.

    I am new to Macromedia Flash so it’s been trial & error; always error …….until YOU.

    Thank you from the very depth of my heart & soul; you truly are an absolute gem for having this here for all of us. May your cup runneth over 3 times over with blessings!!!!!!

  39. Paula Lynch Says:

    Oops! Ok, in the first layer, the first ActionScript works great - can definitely see the pause. In the same layer, where I added the next pause, the ActionScript doesn’t pause.

    I have 4 layers with 2 phrases in each layer that slide in. That means in each layer I need 2 pauses; 1st pause after the first pharse, 2nd pause after the 2nd phrase, then to next layer.

    However, my elation & gratitude from previous post still stands 200%!!
    Thank you, thank you , thank you a million times over!

  40. Paula Lynch Says:

    Got it fixed! I did a new layer naming it ActionScriptPause & put all the pauses in there. Your script works PERFECTLY doing it this way - pause at each phrase.

    Thank you again so very much!!!

  41. David Stiller Says:

    Paula,

    Thanks for the kind words!

    I can’t imagine why Script Assist wanted you to publish as Flash 5, because my example uses ActionScript 2.0 syntax, which wasn’t available until two versions after 5, but ultimately I’m glad you got it working. :)

    I encourage you to keep experimenting with ActionScript. Take it in small steps and build up your confidence as you go. Once understood (as with anything), seemingly magical scripts like the one above unravel neatly into concepts you can combine in new ways to accomplish a whole lot more.

    For sake of clarity, it really makes no difference what layers contain your ActionScript. You can name your layer “scripts,” “actions,” “code,” or nothing at all. You may place four pauses on four different layers, even if those layers contain visual assets.

  42. Ryan Hoshor Says:

    Thanks, David,
    That was *just* the little snippet of code that I needed!
    -Ryan

  43. Leandro Says:

    This script has been really helpful. Easy to understand and to use. Thank you.

  44. Alex Pereira Says:

    It does work for me when i publish locally, but i’m having major problems controlling the clearInterval(interval); from my main movie.

    the structure is: a main swf to which i load external swf slide shows using:
    function wait()
    {
    stop();
    var interval:Number = setInterval(function () {
    trace(interval);
    play();
    clearInterval(interval);
    }, 5000);
    }

    I too get sequntial numbers in the trace (eat your hat!), and i need to work out what path to add to the button code on my main swf to stop the timer.:
    //currently
    clearInterval(interval);

    currently the loading to my holder MC creates erractic picture loads once i have reloaded a new slideshow using the above code due to more than one timer running.

    other than that i love it.

    alex

  45. David Stiller Says:

    Alex,

    By declaring your variable inside the wait() function, you’re scoping the variable to that function alone. Nothing outside the wait() function can see that variable, so while I ate my hat for Lucas, yours is a very different situation. ;)

    Declare that variable outside the function and you should be all right.

    var interval:Number = 0;
    function wait() {
      stop();
      interval = setInterval(function() {
        trace(interval);
        play();
        clearInterval(interval);
      }, 5000);
    }

    … which means that ActionScript outside that function could also clear the interval interval. Keep in mind, you’re going to see incremental values of interval every time the wait() function is called — that’s the way setInterval() works. Until you restart your SWF, Flash will not restart from 1.

  46. Steve B Says:

    Thanks so much i love this AC :) , i’m using Flash MX (6) so i did have to drop the :Number but apart from that sweet

    Your a STAR!

  47. Alex Pereira Says:

    not sure if anything need to be edited here but it’s still not working:

    var interval:Number = 0;
    function wait() {
    stop();
    interval = setInterval(function() {
    trace(interval);
    play();
    clearInterval(interval);
    }, 5000);
    }

    the above code is in my first frame of my show1 and show 2.swf’s and is fired on their timelines calling the function wait();

    On my main swf i have buttons to load the two individual shows

    eg.

    top.but2.onPress = function ()
    {
    //load image show
    _root.block.imageLoad.loadMovie(”images/show1/show1.swf”);
    clearInterval(interval);

    };

    but clicking show 1 and then show 2 buttons is still creating overlapping timers???

    i’m sure i’m missing smething here.
    will the clearInterval(interval); still target the external swf’s setinterval’s?

    Alex

  48. Alex Pereira Says:

    i think i solved it using a full path to the show.swf’s using

    _root.block.imageLoad.stopShow();

    where stopShow is a function

    function stopShow()
    {
    clearInterval(interval);
    }

    but now i have a problem with targeting a var counter in the show.swf. This is a little off track but you can probably tell i’m not quite grasping my paths in this case:

    1st frame of show.swf:
    _root.currentimage=0;
    _root.maxImages = 5;

    function counter()
    {
    _root.currentimage++;
    if (_root.currentimage>maxImages) {
    _root.currentimage = 1;
    }
    if (_root.currentimage

  49. David Stiller Says:

    Alex,

    I can see more clearly now what you’re trying to accomplish. In the case of external SWF files, your ActionScript here …

    top.but2.onPress = function() {
      //load image show
      _root.block.imageLoad.loadMovie(
        "images/show1/show1.swf"
      );
      clearInterval(interval);
    };

    … runs the variable interval through clearInterval() before the external SWF, show1.swf, has even had a chance to load! Whenever you load external files, you must wait until they’re fully loaded before referencing them or operating on them in any way.

    Once loaded, you’ll have to path to the external (now internal) SWF and access its interval variable specifically. You can either do that, as you’ve discovered, by calling a function in the loaded SWF …

    _root.block.imageLoad.stopShow();

    … or simply like this:

    clearInterval(_root.block.imageLoad.interval);

    Pathing is everything. ;) Do what it takes to make those connections! You may want to read the How to Tell when an External SWF has Fully Loaded and Is _root Evil? articles.

  50. Alex Pereira Says:

    I have this working well now, many thanks.

    I was just wondering if this neat bit of code could be adapted as a function that can delay the load of designated MC’s, to build a page progresively without a timeline.

    Alex

  51. David Stiller Says:

    Alex,

    The setInterval() and setTimeout() functions can be used to trigger whatever function(s) you please — so yes, you could adapt the above script to load external SWF files. There are a number of ways to load SWFs at runtime, but I recommend the MovieClipLoader class, as it provides useful events by which you can monitor load progress and completion.

  52. Michael Fletch Says:

    Thanks!

  53. Ann Reynolds Says:

    Thanks for the clear instructions. I googled for
    Setinterval pause flash animation
    and your blog site was the 4th in the list. I tried the kirupa website as I’d been there before but it didn’t help me. I then skipped the next 2 sites and went straight to yours. I’m so glad I did.
    Am using MX2004 and it (and my partner) wanted me to use slightly different code but I held out and yours worked!
    We have now successfully paused the animation for 2 secs while the voice over continues. The animation then plays on and finishes perfectly.
    I’ll be back and maybe have a question, next time!
    Ann

  54. David Stiller Says:

    Ann,

    Wow, thanks! I’m glad to hear that. :) To be fair, I can’t (or shouldn’t) really take credit for the setInterval() approach. There are a actually number of ways to pause a timeline, but the setInterval() function seems to me the most succinct — and easiest to update — so I like it. I wonder if the “slightly different code” your partner expected was an omission of the post colon suffix (the :Number part)? If so, that would work, too. Such suffixes are a feature of ActionScript 2.0 that can bring to light code errors during the compile process and have simply become habit for me. You can drop that suffix and the sample code will still work; in fact, could then be published to ActionScript 1.0.

  55. Ann Reynolds Says:

    The code my partner wanted was prompted by Flash! I insisted that I key in exactly what you had written and it worked. That’s all I’m worried about - making it work!
    Thanks again
    Ann

  56. David Stiller Says:

    Ann,

    You’re welcome! :)

  57. Mooey Says:

    WOW!! this has helped me out so much, I’ve searched and searched for a simple piece of code that would pause the timeline.

    Thanks so much for sharing this :) :)

  58. sharon Says:

    Hi David ~

    I’m not sure if your setInterval is the right actionscript that I need, but it appears to be the one I want.

    Basically, what I want is for the “email_mc” to finish playing (or pause) and have it execute another movieclip after that. I’ve been using onMotionFinished function but cant seem to figure this one out …

    Originally, I had the code like this:

    var AEL1:Tween =new Tween(A_mc, “_y”, Regular.easeOut, 34.9, 44.9, 0.3, true);
    new Tween(A_mc, “_y”, Regular.easeIn, 44.9, 34.9, 0.3, true);

    AEL1.onMotionFinished = function(){
    var AEL2:Tween =new Tween(U_mc, “_y”, Regular.easeOut, 34.9, 44.9, 0.3, true);
    new Tween(U_mc, “_y”, Regular.easeIn, 44.9, 34.9, 0.3, true);

    AEL2.onMotionFinished = function(){
    var AEL3:Tween = new Tween(T_mc, “_y”, Regular.easeOut, 34.9, 44.9, 0.3, true);
    new Tween(T_mc, “_y”, Regular.easeIn, 44.9, 34.9, 0.3, true);

    AEL3.onMotionFinished = function(){
    var AEL4:Tween = new Tween(O, “_y”, Regular.easeOut, 34.9, 44.9, 0.3, true);
    new Tween(O_mc, “_y”, Regular.easeIn, 44.9, 34.9, 0.3, true);

    AEL4.onMotionFinished = function() {
    email_mc.play();
    // >>> here is where i want the next movieclip to play >> “man_mc.play()”
    // >>> but how do i get it to play AFTER the movieclip, email_mc.play() is finished?

    }
    }
    }
    }

    Then I changed it to be similar to yours:

    AEL3.onMotionFinished = function(){
    var AEL4:Tween = new Tween(O, “_y”, Regular.easeOut, 34.9, 44.9, 0.3, true);
    new Tween(O_mc, “_y”, Regular.easeIn, 44.9, 34.9, 0.3, true);

    var interval:Number = setInterval(function () {
    email_mc.play(); //same thing as gotoAndPlay(2)
    clearInterval(interval);
    }, 500);

    AEL4.onMotionFinished = function() {
    man_mc.play();

    }
    }

    Am I missing the punch line?

    thanx
    sharon

  59. Alex Pereira Says:

    Hi David

    going back to your comments on this thread dated ‘January 30th, 2007 at 7:53 am’

    Can you help me elaborate on my effort to load 3 holders sequentially, It’s not working and is not very good actionscript. There is something i’m just not grasping here!!!

    I need to write a function that will load external files in a sequential order. But not using the timeline.

    basically

    load 1
    wait
    load 2
    wait
    load 3
    end

    i have my wait function but my actionscripting is bad from then on:

    var interval:Number = 0;
    function wait() {
    stop();
    interval = setInterval(function() {
    trace(interval);
    play();
    clearInterval(interval);
    }, 2000);
    }

    function sequence() {
    holder1.loadMovie(”images/1sm.jpg”);
    wait();
    holder2.loadMovie(”images/2sm.jpg”);
    wait();
    holder3.loadMovie(”images/3sm.jpg”);

    }

    sequence();

    Any solution or Tuts would be a great help.

    Alex

  60. David Stiller Says:

    Alex,

    For something like this, your best bet is to make sure each image is loaded before proceeding to the next. Waiting two seconds might work, depending on network traffic, but it might not, right? I made a promise that my next blog entry will be about testing when an FLV video has finished playing. As soon as I’ve written that one, I’ll write a tutorial about loading images sequentially. :) I’ll use the MovieClipLoader class, rather than setInterval().

  61. David Stiller Says:

    sharon,

    AEL4.onMotionFinished = function() {
    email_mc.play();
    // >>> here is where i want the next movieclip to play
       >> “man_mc.play()”
    // >>> but how do i get it to play AFTER the movieclip,
       email_mc.play() is finished?

    Since you’re using the Tween class, your best bet is to use the onMotionFinished event, as you did earlier in the code. However, this only makes sense if email_mc is an instance of the Tween class, and I’m not at all sure that it is.

    If email_mc is a MovieClip instance, you could simply put a line of ActionScript in its last keyframe, telling some other movie clip to play. Or you could set up a very short loop with setInterval() to repeatedly check if the value of email_mc’s MovieClip._currentframe property has reached the value of its MovieClip._totalframes property.

    Does that help?

  62. Alex Pereira Says:

    Thanks David,

    I have been looking at the MovieClipLoader class as this is what you mentioned earlier in this thread. It’s a new learning for me and i’m not grasping the whole thing.

    I have got some working eg of MovieClipLoader in my project.
    Whatcode for creating a function should i research to sequential load? to give me a starting point.

    cheers
    Alex

  63. David Stiller Says:

    Alex,

    Your topic is on my to-do list for this blog, but in a nutshell, you’ll set up the first load, then handle the MovieClipLoader.onLoadComplete event to set up the next load, and so on. You could use an array — probably what I’ll do in my blog article — to hold references to each image, and use a variable to step through the array. When the array has been completed, you’ll know you can cancel the event handler.

  64. Jonas Says:

    Hi David,

    I’ve been looking for a similar code like that for AGES!!! thank you, thank you.

    quick question though:
    how can i set this in code in the first frame of my main timeline and then have various mc’s calling it.

    Each mc (eg: “1_mc”, “2_mc”, etc) has 5 small pics that i want to pause after fading in.

    how can i “reference” the code on a specific frame instead of copying the same code all over the place. (editing perhaps 30+ instances of “2000);”

    any ideas?, and THANK you for your generious feedback here u’ve posted here….its really helping me to learn how the code works better.

    Jonas

  65. David Stiller Says:

    Jonas,

    When the playhead encounters ActionScript in a keyframe, it executes that ActionScript first, then updates whatever visuals might need changing. If that ActionScript defines a function, the function is available from that point forward. All you need to do then is correctly reference it. If your function definition is in the main timeline, then a movie clip in that timeline would refer to its parent (this._parent) to get to it. A movie clip nested twice deep would refer to its parent’s parent (this._parent._parent) to reach the main timeline. Does that help?

    In this case, you’d have to wrap the timing mechanism — the setInterval() part — into a function and probably pass in a reference to the timeline (the movie clip) that wants to use it; otherwise the play() function wouldn’t know whose timeline to start up again.

    Alternatively, you could keep all your code in the main timeline and just path out to the desired movie clips.

    mc_1.stop();
    mc_1.interval = setInterval(function () {
      mc_1.play();
      clearInterval(mc_1.interval);
    }, 2000);

    P.S. Movie clip instance names follow the same rules as variables: they shouldn’t start with a number, so notice that I swapped the characters.

  66. Mike C. Says:

    David,

    Likewise I am awed by the simplicity of this code. Bravo! I do have another question though, I’ve created a learning interaction in Captivate 1.0, published as a swf. I’m using an authoring tool that requires a separate “wrapper” to communicate with our LMS. With Captivate, I have no access to a .fla file, therefore I can’t use action script to communicate with the external wrapper. So, I’ve built a simple timeline in Flash and using the loadMovie function, I’m calling in the Captivate generated swf.

    That works fine and your pause works great with .swfs that play on a definite timeline, but, since the interaction I have requires questions to be answered by the learner, progress will vary, therefore, I can’t enter a specific time for the swf. Do you have some magic code that will pause the main flash timeline until the external swf is through playing then resume?

    Mike C.

  67. David Stiller Says:

    Mike C.,

    Even if you don’t have the source FLA for a SWF, manipulation of that SWF is still within the realm of possibility via ActionScript. Once loaded, the formerly external content becomes available to internal programming under the auspices of the MovieClip class. This means you could set up a loop, for example to check the loaded SWF’s MovieClip._currentframe property against its _totalframes property to see when the former meets the latter.

    _root.onEnterFrame = function():Void {
      if (loadedClip._currentframe >= loadedClip._totalframes) {
        trace("Bingo!");
      }
    }

    Note: See “How to Tell When an External SWF has Fully Loaded,” otherwise my suggestion is moot.

    In addition, this depends entirely on how the loaded SWF operates. It might have nothing more than a single-frame timeline — everything run and animated with ActionScript — in which case the properties I just mentioned will be equal to each other from the start. I don’t have any experience with Captivate, so I’m not sure how it makes the SWFs it does.

    Of course, you could always provide a button that invokes MovieClip.play() on the loaded SWF — that way the user can decide! :)

  68. Alex Pereira Says:

    I have become confused with this code!!! I’ve been playing around with MovieClipLoader.onLoadComplete (but i still not got the full grasp of it) My actionscript is as follows:

    //ten second pause
    var interval:Number = 0;
    function wait() {
    stop();
    interval = setInterval(function() {
    trace(interval);
    clearInterval(interval);
    }, 10000);
    }

    //attach holder and preloader
    this.attachMovie(”holder”, “holder1″, 1,{_x:0, _y:0});
    this.attachMovie(”progress”, “progress1″, 2,{_x:35, _y:0});

    my_mc = new MovieClipLoader();
    preload = new Object();
    my_mc.addListener(preload);

    preload.onLoadStart = function(targetMC) {
    trace(”started loading “+targetMC);
    holder1._alpha = 0;
    progress1._visible=true;
    };

    preload.onLoadProgress = function(targetMC, lBytes, tBytes) {
    progress1.pText.text = Math.round((lBytes/tBytes)*100)+”%”;
    };

    preload.onLoadComplete = function(targetMC) {
    slowfadeIn(holder1);
    progress1._visible=false;
    trace(targetMC+” finished”);
    };

    function loadRandom()
    {
    choice = Math.round(Math.random()*4+1);
    switch (choice) {
    case 1 :
    my_mc.loadClip(”images/intro01.jpg”, “holder1″);
    break;
    case 2 :
    my_mc.loadClip(”images/intro02.jpg”, “holder1″);
    break;
    case 3 :
    my_mc.loadClip(”images/intro03.jpg”, “holder1″);
    break;
    case 4 :
    my_mc.loadClip(”images/intro04.jpg”, “holder1″);
    break;
    case 5 :
    my_mc.loadClip(”images/intro05.jpg”, “holder1″);
    }
    }

    What i really need to do is put a 10 sec delay ( wait function) on what ever image loads from my random load function. ( to allow animations to run first)Is the interval = setInterval(function() etc. only good for a timeline pause, or can it be used to pause actionscript firing in a single frame?

    just not getting it!!!

    Alex

  69. Kerry Says:

    Rookie question, can you help?

    I need my flash movie to pause (at any point in time) by hitting the spacebar, and resume by hitting enter key. This code is not working:

    Key.addListener(this);
    this.onKeyDown = function() {
    if (Key.isDown(Key.SPACE)) {
    _root.stop();
    }
    if (Key.isDown(Key.ENTER)) {
    _root.play();
    }
    };

    What am I doing wrong? I’ve put the action script in the first frame of the movie. Please help!

  70. David Stiller Says:

    Kerry,

    You’re on the right track! Listeners in ActionScript 2.0 are a little “loose” in that they’re configured differently depending on the object doing the listening. (AS3 improves things by bringing consistency in this area.) Instead of adding this to the Key class, you’re going to need a generic Object to act as your “liaison” for the onKeyDown event. Give this article a look and see if it helps you out; if not, I’ll tell you the answer, quick-like. :)

  71. David Stiller Says:

    Alex,

    You’re pretty close. :) In a situation like this, I would probably call that custom wait() function from the onLoadComplete event handler. (Note: Check the MovieClipLoader class entry for the difference between the onLoadComplete and onLoadInit events, in case you want to use the latter.)

    That way, once each image loads, your slowFadeIn() function is called, progress1’s _visible property is set to false, and finally … you’d invoke that wait() function — which would, in turn, call loadRandom()

    function wait() {
      stop();
      var interval:Number = setInterval(
        function():Void {
          loadRandom();
          clearInterval(interval);
        },
        10000
      );
    }
  72. Christian Says:

    Hi David,

    I have a similar problem as Kerry did re: stopping/starting the timeline using the ENTER key. I got the actionscript to work after reviewing her code and your link to listeners.

    I put the following in the first frame of the scene

    var keyListener:Object = new Object();
    keyListener.onKeyDown = function() {
    if (Key.isDown(Key.ENTER)) {
    _root.stop();
    }
    };

    keyListener.onKeyDown = function() {
    if (Key.isDown(Key.ENTER)) {
    _root.play();
    }
    };

    When I preview the scene, the script works perfectly! The strange part is when I open the “named_scene.swf” the script doesn’t seem to want to cooperate. I’d appreciate any thoughts and suggestions.

  73. Christian Says:

    Follow up: I can post/email you a test .fla to illustrate the anomaly. Also pardons to Kerry on assuming it was “her” code. I used “his/her” code as the starting point and got things to work. Thanks Kerry.

  74. David Stiller Says:

    Christian,

    In your first comment, I notice you’ve got the Enter key both stopping and starting the main timeline (probably just a typo … but I thought I’d bring it up). Based on your follow up, it sounds like you got it to work after all. If not, let me know. :)

  75. Christian Says:

    Hi David,

    post-post follow-up. The following code seems to work too as sent to me via a friend of a friend, but have found that pressing Ctrl-Enter can pause/start with 100% accuracy, while simply pressing ENTER yields 50% reliability when using this code in different scenes. (in the .exe or .swf) For example: Scene 1, 3, 5 the Enter key stops/starts as planned. Whereas Scenes 2, 4, 6, nothing happens. Pressing Ctrl-Enter (in the .exe or .swf), the scenes stop/start as intended.

    Whew! I guess.

    ——————-

    _global.playToggle = true;

    this.keytext.text = “Tells you what key is being pressed”;
    var keyListener:Object = new Object();
    keyListener.onKeyDown = function() {
    displayStroke(Key.getCode(),”DN”);
    }
    Key.addListener(keyListener);
    function displayStroke(stroke,keyMotion){

    this.keytext.text+= “| ” + stroke + “, ” + keyMotion + ” |\r”;
    switch(stroke){
    case 13:
    toggleState(this);
    //do something else
    break;
    default:
    break;
    }
    }
    function toggleState(scope){

    if(_global.playToggle == true){
    scope.stop();
    _global.playToggle = false;
    } else {
    scope.play();
    _global.playToggle = true;
    }

    }

    ————————

    Hope this helps all who may come across your site.

    Best!
    Christian

  76. alex Says:

    Hi David

    Back again, confused again!!!

    i have a stop on frame 1

    i have this code on frame 9 to pause my timeline:

    stop();
    var interval:Number = setInterval(function () {
    play();
    clearInterval(interval);
    }, 5000);

    frame 10 has gotoAndStop(1);

    So why when it runs do i not get the movie to stop on frame 1 again, it keep looping? What am i missing!

    cheers
    Alex

  77. alex Says:

    hey i have worked it out, but need a solution!!!

    i need to pause the timeline using player 6 actionscript 1.0, if i convert to V8 and 2.0 it stops as i want it to at the cost of losing other code functionality!

    any ideas

  78. alex Says:

    guess what i have got this working in V6 actionscript 2.0 and kept all the other stuff i need, so forget the questioning! and delete if necessary ;)

  79. David Stiller Says:

    alex,

    No worries! No need for deletion. The reason your movie continued looping is because ActionScript 1.0 doesn’t use strong typing. The var interval:Number wasn’t registering because of the :Number in that version of the language, so there really wasn’t an interval variable to reference in the clearInterval() function call. Because of that, the play() keeps getting called every five seconds. For ActionScript 1.0 SWFs, drop the :Number and it works out fine.

  80. Fred Says:

    David
    Thanks so much for your simple to understand instructions on how to pause or slow down time with out adding a ridiculous number off frames. Many moons ago I authored in Director (6) and have recently taken on the challenge of teaching myself flash. Boy I miss the tempo function of Director and can not help but wonder why none of the books I read addressed this simple but required code. Thank you so much.
    Fred AKA cpt video

  81. David Stiller Says:

    Fred,

    Hey, glad to hear it! As it happens, I started with Director 6.5 myself and was very reluctant to pick up Flash a couple years later. Stick with it, though! It does gel eventually! ;) And you can go right on using both apps.

    Sooner or later, I’ll have to go back and update some of the more popular entries, like this one, for ActionScript 3.0. In this mean time, this 2.0 version will do the trick, even in Flash CS3 (aka 9), as long as you configure the publish settings accordingly.

  82. Eric Martin Says:

    Hi… I need a really simple script, I need to pause the timeline, either on the main timeline or on a movieclip. I just need something simple and after a day of searching can’t find anything!!!

    Please help, I need to have it created for as3.

    Thanks.

  83. David Stiller Says:

    Eric,

    See this new article here. :)

  84. Steve Says:

    Thank You David. I simply wanted to pause a MC and the frameTo(alternate solution) from the zigo classes isn’t working for me, which is going to pose some other problems with my project. I put your code in my movieclip and bam….answered.

    Again, Thank you.

    Cheers,
    Steve

  85. David Stiller Says:

    Steve,

    Thanks!

  86. io Says:

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

    Thanks, 木頭

  87. pj Says:

    Hi David,

    You sure have made a lot of people happy with your code.

    I can get it to work on the first image but i cant get it to work a second , third, fourth etc.. Once i place the same instance of the code into the actions layer for the second time it no longer works at all.

    My flash file is made up of 10 images on 10 layers and they fade in & out every 10 keyframes. basic stuff in CS3. Any reason why it wouldnt work once i add a second instance?

    I am a n00b at Actionscripting so I am sorry for me ignorance! =D

    Pen

  88. Eric Walton 9 / Edub9 Says:

    Quick question for you, here is the code I am using on every keyframe in my movie. It is a timer and works perfectly. However I need to have a set of buttons on another layer to pause and resume by clicking and I cannot seem to get them to work. I have read every thing there is and for the life of me I cant figure out why they wont work?
    Any ideas?

    Edub9

    TIMER CODE BELOW

    _root.pauseCount = 0;
    function pause(pc)
    {
    if(_root.pauseCount == pc)
    {
    clearInterval(pauseInt);
    play();
    }
    else
    {
    _root.pauseCount++;
    }
    }
    pauseInt = setInterval(pause, 0, 300);

    stop();

  89. David Stiller Says:

    To io …

    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

    To Pen …

    If you’re using Flash CS3, make sure your document’s Publish Settings are configured for ActinScript 2.0 (the new default is 3.0, though the choice is yours) — either that, or use the AS3 version suggested here.

    And if you’re still stuck, be sure to write back. :)

    To Edub9 …

    I think I understand what you’re after. The pausing (and playing) done by the ActionScript is triggered by each keyframe on which the playhead pauses, and it sounds like you want buttons to be able to override that; in other words, stretch the current pause indefinitely (a pause as triggered by a button) or resume playback immediately (a play as triggered by a button). If that’s it, then you’ll need to wire up such functionality to the buttons themselves, and I think all you’ll need is to invoke clearInterval() on the Pause button and play() on the Play button.

    // In frame 1 ...
    var pauseInt:Number;
    // declares the variables globally
    // in this timeline
    
    btnPause.onRelease = function():Void {
      clearInterval(pauseInt);
      // simply sidesteps the timer's eventual
      // triggering of play()
    }
    
    btnPlay.onRelease = function():Void {
      play();
      // simply advances the timeline, which
      // will come to another programmed
      // pause sooner or later
    }
    
    // In subsequent frames ...
    stop();
    pauseInt = setInterval(
      function():Void {
        play();
        clearInterval(pauseInt);
      },
      2000
    );
  90. Eric Walton 9 / Edub9 Says:

    Thanks for the quick reply, sorry it took me so long to get back to you.

    So the below is what I would use on the play and pause button?

    btnPause.onRelease = function():Void {
    clearInterval(pauseInt);
    // simply sidesteps the timer’s eventual
    // triggering of play()
    }

    btnPlay.onRelease = function():Void {
    play();
    // simply advances the timeline, which
    // will come to another programmed
    // pause sooner or later
    }

    And the buttons name would be btnPause?

    Thanks again,

    Eric

  91. Eric Walton 9 / Edub9 Says:

    Hey David, I tried a bunch of variations on the above but I guess the easiest thing I would need to figure out is the code for a stop or off / on button that would stop everything. This should be easier for me I am very very very rusty. Lemme ask you would it be cleaner or easier if I used one large bit of code for all? But i do need to time each keyframe individually so I don’t think that would be the answer.

    Thanks buddy,

    Edub9

  92. David Stiller Says:

    Edub9,

    When you say “stop everything,” it occurs to me now that you may mean stopping the timeline itself in addition to bypassing the setInterval() trigger that restarts an already paused timeline.

    I also see a typo in my suggested code: I gave the same instance name, btnPause, to both the Pause and Play buttons. That pretty much breaks everything, causing the timeline to simply play every time. Sorry about that! (I’ve corrected my previous reply as well as yours.)

    Lemme ask you would it be cleaner or easier if I used one large bit of code for all?

    Size doesn’t always matter (so they say), and that holds true in this case. ;) I didn’t clarify that the Pause and Play buttons can, and should, span the full length of the timeline in the above example. You wire them up in frame 1, and their programming holds for the duration of their presence. That way, you have minimal effort on the buttons and maximum flexibility on each pause, because each keyframe code could specify its own duration to pause in milliseconds.

    Check out the revised instance names in our previous replies and compare that with the following button code, which removes the unneeded comments and adds a single call to stop().

    var pauseInt:Number;
    
    btnPause.onRelease = function():Void {
      stop();
      clearInterval(pauseInt);
    }
    
    btnPlay.onRelease = function():Void {
      play();
    }

    The above would go in frame 1. Note, as before, that the pauseInt variable is declared at this point, which ensures that later references to it point to the same variable (in the original article, this was interval, but it doesn’t matter what you call the variable).

    In later frames, you wouldn’t have to use var to re-declare the variable. On any frame that needs pausing, use:

    stop();
    pauseInt = setInterval(
      function():Void {
        play();
        clearInterval(pauseInt);
      },
      2000
    );

    … swapping the 2000 for whatever time duration you please.

    Bear in mind that if your first setInterval(), as just shown, is on frame … oh, 100, and the user happens to click the Pause button on frame 99, the timeline will stop. Everything will stop, which I think is what you’re asking. When the user hits play, the playhead will hit frame 100 within a fraction of a second, and the timeline will pause again — because of the stop() function on that frame.

  93. Eric Walton 9 / Edub9 Says:

    David, still having problems….

    OK, so I have 3 control layers in my flash.

    1. pause_play_controls
    in this frame i have 2 buttons named

    play_btn
    this has this code on it

    btnPlay.onRelease = function():Void {
    play();
    // simply advances the timeline, which
    // will come to another programmed
    // pause sooner or later
    }

    pause_btn
    this has this code on it

    btnPause.onRelease = function():Void {
    clearInterval(pauseInt);
    // simply sidesteps the timer’s eventual
    // triggering of play()
    }

    2. pause_layer
    with this on all frames

    // In subsequent frames …
    stop();
    pauseInt = setInterval(
    function():Void {
    play();
    clearInterval(pauseInt);
    },
    3000
    );

    3. frm1_vars
    with this in first frame spanning entire movie

    // In frame 1 …
    var pauseInt:Number;
    // declares the variables globally
    // in this timeline

    Here is the debug output………

    **Error** Scene=Main, layer=pause_play_controls, frame=2:Line 1: Statement must appear within on handler
    btnPlay.onRelease = function():Void {

    **Error** Scene=Main, layer=pause_play_controls, frame=2:Line 1: Statement must appear within on handler
    btnPause.onRelease = function():Void {

    Total ActionScript Errors: 2 Reported Errors: 2

    Not sure what to do at this point? Sorry to be a pain in the A****

    Edub9

  94. David Stiller Says:

    Edub9,

    haha … Man, don’t worry about being a pain. I don’t think you’re being one.

    The problem you’re seeing is the result of your attaching the code directly to your buttons. If you were doing that, you wouldn’t need to give your buttons instance names (e.g. btnPause) because ActionScript would clearly know which button was supposed to do what. See my “Museum Pieces” article for details.

    So really, you can get away with a single scripts layer for your code. The ActionScript in bullet point 1 of your last reply, as well as the ActionScript in bullet point 2, will all go into the scripts layer. Make sure to add the stop() reference to the Pause button’s event handler.

    Where bullet point 2 says “with this on all frames,” keep in mind, the setInterval() code only goes in keyframes where you want the timeline to pause. It certainly can go on all subsequent frames, but you may likely have frames in between that use tweens to transition from one visual concept to the next — those frames shouldn’t have the setInterval() code or stop().

    The code in your bullet point 3 should go in frame 1 of your scripts layer, along with the button event handlers.

  95. Eric Walton 9 / Edub9 Says:

    Ok, I think I sort of get it now. BUT I have each an every frame with animated text and or images flying into it this content is embedded into a movie. In other words i have 27 animated mc’s placed into 27 pages.

    I may be going about this all wrong. Here is what I need ……

    ALL the frames with an automatic pause code in seconds.

    And

    All the frames need the ability to be paused and restarted manually via a button.

    Should I be approaching this in a different way? Damn I hope not….

    Would you like me to email the source file to you, maybe that will help?

    Thanks again,

    Edub9

  96. Eric Walton 9 / Edub9 Says:

    BTW You rock so HARD!!!!!

    Edub9

  97. David Stiller Says:

    Edub9,

    To be honest, I’m not sure I can 100% visualize what you mean by “27 animated mc’s placed into 27 pages,” because Flash doesn’t have anything technically called “pages” — but … I think that you’re saying is that your main timeline (which has the setInterval() pause/play code) also contains a number of nested movie clips, each of which has their own animations. It sounds like you want to pause not only the main timeline, but also those nested movie clips.

    If that’s it, the above should still work just fine for the main timeline, but you’re also going to have to address each of those nested clips by instance name and invoke MovieClip.stop() on them (then MovieClip.play() later). That means you’ll either have to give each an instance name manually and add to your pause/play code, something along the lines of this:

    btnPause.onRelease = function():Void {
      stop();
      childClip01.stop();
      childClip02.stop();
      childClip03.stop();
      // etc.
      clearInterval(pauseInt);
    }
    
    btnPlay.onRelease = function():Void {
      play();
      childClip01.play();
      childClip02.play();
      childClip03.play();
      // etc.
    }

    But that could get a bit tedious. For one, you’d have to give each of those clips an instance name (e.g., childClip01, or some other descriptive, but unique name for each), and for two, it may not even be the case that all of those clips are present on any given frame.

    It would be more flexible to cycle through all the children of the main timeline, whatever they are, and then stop or play them as appropriate of they’re movie clips. You could use a for..in loop, in cahoots with the array access operator, for that (see “How to Reference Objects Dynamically” for more detail).

    btnPause.onRelease = function():Void {
      stop();
      for (var clip:String in this._parent) {
        if (typeof(this._parent[clip]) == "movieclip") {
          this._parent[clip].stop();
        }
      }
      clearInterval(pauseInt);
    }
    
    btnPlay.onRelease = function():Void {
      play();
      for (var clip:String in this._parent) {
        if (typeof(this._parent[clip]) == "movieclip") {
          this._parent[clip].play();
        }
      }
    }
  98. Eric Walton 9 / Edub9 Says:

    Nope, nothing that complicated is necessary. All I need to do is have a pause/play button that will stop each of the 27 keyframes (27 pages) from advancing after the pause code you see below.

    _root.pauseCount = 0;
    function pause(pc)
    {
    if(_root.pauseCount == pc)
    {
    clearInterval(pauseInt);
    play();
    }
    else
    {
    _root.pauseCount++;
    }
    }
    pauseInt = setInterval(pause, 0, 300);

    stop();

  99. David Stiller Says:

    Edub9,

    We’ve come full circle! ;) Okay, here’s my understanding:

    All I need to do is have a pause/play button …

    So far, so good. One button that either pauses or plays, as needed.

    … that will stop each of the 27 keyframes (27 pages) from advancing …

    Where are these keyframes? In the main timeline? What happened to the 27 animated movie clips?

    … after the pause code you see below

    The given pause code doesn’t make much sense to me, I’m afraid, and that might be because I’m seeing it out of context. Check it out:

    _root.pauseCount = 0;

    So far, we have an arbitrarily named variable pauseCount, initialized to a value of zero.

    function pause(pc) { ... }

    Now we have a custom function, pause(), that accepts one parameter.

    pauseInt = setInterval(pause, 0, 300);

    Here we’re triggering that function every zero (!) milliseconds and passing it a value of 300. So let’s see what pause() actually does:

    if(_root.pauseCount == pc)

    If pauseCount equals 300 (the passed in value, pc), then …

    clearInterval(pauseInt);
    play();

    … kill the setInterval() loop and play; otherwise …

    _root.pauseCount++;

    … increase the value of pauseCount by 1. So when the playhead enters the frame that contains this code, the custom pause() function is going to be executed 300 times as fast as Flash can possibly handle it, then play. That code might just choke Flash Player, because setInterval() is being asked to repeatedly trigger the pause() function every zero milliseconds. Over all, it’s much less complex (which is usually good) to simply use this:

    stop();
    var pauseInt:Number = setInterval(
      function():Void {
        play();
        clearInterval(pauseInt);
      },
      300
    );

    Which would pause the timeline for 300 milliseconds (approx one third of a second). So, if I’m understanding you, you want a pause/play button to stop 27 keyframes (of perhaps 27 movie clips [?]) after that point.

    Wherever those movie clips are, you’re going to have to reference them by instance name or for..in loop and invoke MovieClip.stop() or MovieClip.play() on them.

  100. Eric Walton 9 / Edub9 Says:

    Actually the pause

    stop();
    var pauseInt:Number = setInterval(
    function():Void {
    play();
    clearInterval(pauseInt);
    },
    300
    );

    needs to be on every keyframe and run automatically.
    the one I posted previously pauses for 3 seconds.

    So If I use the above pause code will it run automatically?
    And then could I place a button with play and pause on a different timeline
    and in each keyframe to stop the automatic advancing to next frame?

    So once again basically all I am looking for is a movie that runs through each keyframe automatically and each keframe is set to a certain number of seconds.

    But this also needs to have additional functionality to manually pause each frame. Or after you have finished reading the content on said frame you can press next to begin the automatic advancing again.

    In other words if you let the movie run by itself it will need no user interaction but you can pause or play in any of the frames. Just like a powerpoint presentation but with a better look.

    Also as far as the mc’s go If I need to I will use static text instead of animated text like I am doing now.

    Do you want me to email it to you? If so send me a message and I will.

    Make sense?

    Thanks soooo much,

    Edub9

  101. David Stiller Says:

    [Follow up on Edub9 …]

    It turns out there were three issues with Edub9’s file: a) the instance name on his Play button was not the same as the instance name (btnPlay) referenced in the ActionScript, b) the Pause button had no instance name at all, and he had two different variable names for the setInterval() return value (interval and pauseInt), which actually needed to be the same — so he was calling clearInterval() from the button event handlers on a different (non-existent) variable from the one returned by setInterval().

    With these corrections, the file worked as expected.

  102. Irina Says:

    Hi guys! sorry to but in… but i have a problem and i have no idea how to solve it. i am building an ActionScript 2.0 projector using CS3. In one of my frames, the user can click a button and my app launches an .exe (let’s call it “a.exe”. I need to pause my timeline until the user closes “a.exe”. Obviusly, i have mo ideea how long it will take, so i cannot use intervals.
    I am launching a.exe using fscommand with exec; fscommand returns immediately after launhing a.exe… so I cannot rely on that to pause my presentation.
    Any ideas?

    Thx

  103. David Stiller Says:

    Irina,

    For better or worse, Flash keeps no record of the apps it launches via the exec command for fscommand(). You may be able to find this sort of functionality with a 3rd party Projector wrapper — check out mdm ZINC, for example, or FlashJester Jugglor — but make sure to ask those vendors for specifics. I recently completed a sizable project for someone using ZINC and found that, while an excellent piece of software, it wasn’t able to keep track of external applications … but my memory is rusty on that, so ask! :)

    The only reliable workaround I can think of is to display a “click to resume” message in your Flash movie, which would allow the user to get back into the action with no more than a single (one would hope not annoying) click.

  104. Eric Walton 9 / Edub9 Says:

    Hey David, it’s your favorite guy!
    Just droppin by to say hello and to let you know my presentation is working out splendidly. However you have not heard the end of me! LOL!!!!!

    Cheers,

    Eric Walton 9 / Edub9

  105. Charlie Says:

    I have absolutely no experience with actionscript. This is only my second attempt at flash.

    I thought what I wanted to do was simple enough. Like you wrote, instead of having scores of extra frames to pause a movie, I would pause the movie for x number of seconds so that pictures fading in and out would pause in-between the fades and display a looped slideshow.

    I created a new layer, added a keyframe, right-clicked on the frame chose “actions” pasted in the exact code you posted:

    stop();
    var interval:Number = setInterval(
    function():Void {
    play();
    clearInterval(interval);
    },
    2000
    );

    Saved the file and tested the movie.

    I got the following error:

    Description:
    1046: Type was not found or was not a compile-time constant: Void.

    I am using Flash CS3 with actionscript 3.0

    What am I doing wrong?

  106. David Stiller Says:

    To Edub9 …

    Glad everything’s working!

    To Charlie …

    In ActionScript 3.0, the term Void has been changed to the lowercase void, but revising that isn’t going to be your best bet, in this case. In AS3, the recommended approach toward timed triggering is no longer setInterval() or setTimeout(); instead, you’ll want to use the Timer class, as described in “How to Pause a Timeline (AS3).” If you want to use the AS2 version, as shown above, you’ll have to configure your FLA’s publish settings for ActionScript 2.0; otherwise, use the new approach in the other article. :)

  107. Mary Anne Says:

    How to Pause a Timeline (AS2)

    Mr. Stiller…you just saved me days of trying to figure out how to pause a timeline. I’m a newbie to Flash and still in the womb when it comes to coding in ActionScript. Thank you!!!

  108. David Stiller Says:

    Mary Anne,

    So glad I could help! I hope you get more out of the rest of the blog. :)

  109. Emanuel Says:

    David, I am trying to make a scrollbar that can scrub the timeline of a loaded movieclip as well as pause it using code thats in the main (parent) movieclip. Do you have any suggestions or hints to where I can go to complete that task. Both _current frame and setInterval are not being scoped, is there another way to read information (if its stop, playing or have ended) from a loaded movieClip?

    Help Please

  110. David Stiller Says:

    Emanuel,

    The setInterval() function might be causing your scope issues. Are you using the alternative approach to setInterval() (the one that allows you to specify scope)? Even if you don’t use that approach, I find that I can load a SWF and tell it to run backwords just fine. Note that I’m addressing the loaded content by its container’s instance name, rather than the possible incoming parameter, which I’ve arbitrarily named mc. Check it out:

    var container:MovieClip = this.createEmptyMovieClip(
      "container",
      this.getNextHighestDepth()
    );
    
    var frames:Number = 0;
    
    var mcl:MovieClipLoader = new MovieClipLoader();
    var listener:Object = new Object();
    listener.onLoadInit = function(mc:MovieClip) {
      container.stop();
      frames = container._totalframes;
      setInterval(
        function():Void {
          container.gotoAndStop(frames--);
        },
        33
      );
    }
    mcl.addListener(listener);
    
    mcl.loadClip("backerds.swf", container);
  111. Emanuel Says:

    Got the setInterval working but now I just have a simple problem that I hope someone can solved. Is there anyway to get the play command from a movieclip to read a variable that was generated from an equation. My scrollbar for scrubbing a loaded movieclip timeline keeps playing when it last stop as if I paused it. It needs to play from the new scrollbar location.

  112. David Stiller Says:

    Emanuel,

    If you’re talking about the MovieClip.play() method, you’ll find that play() doesn’t accept any parameters — but gotoAndPlay() does. As long as your equation resolves to an integer, you may use that equation as your parameter.

    Reference the movie clip by its instance name, invoke the MovieClip.gotoAndPlay() method, and supply your equation:

    myClip.gotoAndPlay(5 + 5);

    That would send myClip to frame 10 of its own timeline.

  113. Emanuel Says:

    The Movieclip still snaps back to where ever I first grab it.
    Here’s the code … it should work but it doesn’t. I wish I could clear the movie clips memory of where it can from but it just retains it.

    // —–release
    vcrControls_mc.sliderBox_mc.slideBall_mc.onRelease = function() {
    stopDrag();
    sliderAmount = (vcrControls_mc.sliderBox_mc.slideBall_mc._x/104);
    playWhenReleased = (MCholder._totalframes * sliderAmount);
    //playWhenReleased = playWhenReleased/1000;
    MCholder.gotoAndPlay((MCholder._totalframes * sliderAmount)/100);
    delete this.onMouseMove;
    //this.onReleaseOutside = this.onRelease;
    vcrControls_mc.sliderBox_mc.pausePlay_mc.gotoAndStop(1);
    onEnterFrame = actionPack;
    //gets rid of studder scrubbing bu packing functions in onEnterFrame
    };

  114. David Stiller Says:

    Emanuel,

    There’s quite a bit going on here that is completely unknown to me, such as your variables sliderAmount and playWhenReleased, as well as the onMouseMove and onEnterFrame stuff (where is actionPack declared?).

    I’m afraid I just can’t see clearly what you’re aiming for (where’s setInterval(), for example?).

    This sounds like a perfect opportunity for divide-and-conquer troubleshooting. Break down your code, including everything the above snippet requires, into compartmentalized sub-goals. Make sure you understand exactly what’s going on inside each sub-goal in isolation. That’s right, save your work, as is, for the time being and recreate the operative sub-goals in brand new FLAs. Something is — possibly, quite a few things are — going on here that you may not even be aware of yourself.

  115. Emanuel Says:

    Thank You
    David, I tried your advice however even with a simple gotoAndPlay statement attach to a button and a input box (for timeline location), my movieclip only resumes from where it stopped and not from where I had input a new time interval. Its as if the movieclip time information from the stop command bogarts all else.

    The setInterval …can it become indefinite?

  116. David Stiller Says:

    Emanuel,

    I mentioned setInterval() because your first post mentioned it, and you observed that setInterval() somehow wasn’t scoping properly. I was surprised not to see it, actually, in your later code sample.

    I’m still not clear on how you’re loading the content that gets scrubbed. Given the suggested code in the actual blog entry, I’m guessing that you’re using setInterval() somewhere, but I’m not sure where. If you’re loading content and scrubbing that, or just pausing it, you may not even need setInterval().

    In my mind, you’re creating a kind of FLVPlayback mechanism, but for SWFs instead of FLVs. If that’s it, you probably have a pause button that stops the timeline of the loaded content. For that, all you really need is to have that button invoke MovieClip.stop() on the loaded content, and MovieClip.play() to resume it. If the loaded content happens to use the setInterval() code in its own timeline, then the mechanism that controls it — that scrubs it — must cancel the loaded content’s interval by invoking clearInterval() on the variable inside the loaded content that holds the return value of setInterval().

    Am I getting closer to what you need? :)

  117. virendra Says:

    U did a good job

    thanx…

  118. David Stiller Says:

    virendra,

    Thanks!

  119. James Says:

    david…..

    awesome! I was sitting there racking my brain trying to come up with a solution for this today and i scanned through my bookmarks and found a link to your site and Bingo! problem solved.

    Your work is muchly appreciated.

    Cheers from Australia!

  120. David Stiller Says:

    James,

    Super! Cheers right back. :)

  121. Jimmy Says:

    Thanks for posting this; I found it very helpful.

  122. rob Says:

    thanks for this! it’s just what i needed.

  123. David Stiller Says:

    To Jimmy …

    You’re welcome!

    To rob …

    Glad to hear it. :)

  124. Konstantin Says:

    David, tried your script.
    However, for me, works fine in preview untill published…settings: flash8 as2
    what i need: pause timeline and play other_mc, during pause
    When published and viewed in IE, somehow the pause is shortened…and not all of other_mc is played

    thanks

  125. David Stiller Says:

    Konstantin,

    Based on your description alone, I’m afraid I can’t tell what’s going wrong. The SWF shouldn’t behave any differently in IE than it does in any other browser. Does your SWF work fine in, say, Firefox or Safari?

  126. nathan Says:

    Hey There!

    Great tutorial, thank you so much for it and your continued efforts to help the community apply it.

    Which of course, leads us to the never ending scenario of putting tested scripts into a wide variety of environments.

    My particular issue is that I have your interval script attached to a button’s onRollOver, onRollOut, and OnRelease behaviors as I’m creating a bit of a rollover navigation system. Simple so far, but I’m finding that when I activate the OnRelease function (which is supposed to change the onRollOut behavior), it resets the button’s onRollOver state. This results in erasing the new onRollOut behavior for the default one that’s called if a user doesn’t click on the button.

    It’s hard to explain, so…

    var intervalStatus:String = “closed”;

    btn1.onRollOut = function() {
    var interval:Number = setInterval(
    function():Void {
    if (intervalStatus == “open”) {
    // event
    gotoAndPlay(3);
    } else {

    }
    clearInterval(interval);
    },500
    );
    }

    btn1.onRollOver = function() {
    gotoAndPlay(4);
    }

    btn1.onRelease = function() {
    var intervalStatus:String = “closed”;
    }

    thanks for your help!

  127. David Stiller Says:

    nathan,

    Great tutorial, thank you so much for it and your continued efforts to help the community apply it.

    Sure thing, bro. :)

    Which of course, leads us to the never ending scenario of putting tested scripts into a wide variety of environments.

    Ha! That does happen — and your usage is pretty interesting. In fact, my first reaction was something like, “Hrm … I’m not sure this is a good idea….” But in theory, I suppose it should be fine. Going in order of occurrence, the first thing that happens is (probably) the onRollOver event handler, which sends the timeline to frame 4. At this point, the user’s mouse is over btn1. The user could sit there for half an hour, and nothing would happen, because the onRollOver handler has already done its thing. Now, let’s imagine the user changes her mind and pulls the mouse away from the button. At that moment, the onRollOut event is handled. This handler does the following:

    • Sets a looping interval every 5 seconds
    • If intervalStatus is "open", the timeline is sent to frame 3
    • If not, the looping interval is cleared — otherwise this function repeats every 5 seconds

    The only thing that changes intervalStatus to something other than "open" is the onRelease event handler. So … if the user happened to click the button before pulling the mouse away, the loop would stop; otherwise, it will continue to send the timeline to frame 3 every 5 seconds. I’m thinking you might actually want to kill the loop in either case — just that the frame would change when intervalStatus isn’t "open".

    Now, you’re saying the onRelease handler somehow erases the onRollOut handler, which doesn’t seem right. I think that’s actually going on is that you’re declaring two different intervalStatus variables. One is declared in the main timeline and the other is specifically scoped to the btn1 instance. Drop the var and :String inside the onRelease handler and see if that helps. I would probably declare the interval variable outside of the function, as well:

    var intervalStatus:String = "closed";
    var interval:Number = 0;
    
    btn1.onRollOut = function():Void {
      interval = setInterval(
        function():Void {
          if (intervalStatus == "open") {
            // event
            gotoAndPlay(3);
          }
          clearInterval(interval);
        },
        500
      );
    }
    
    btn1.onRollOver = function():Void {
      gotoAndPlay(4);
    }
    
    btn1.onRelease = function():Void {
      intervalStatus = "closed";
    }

    Note that I changed your else clause a bit.

    I’m not sure the above is what you need, but worth a shot. :)

  128. nathan Says:

    hey david,

    thanks for fixing this. from my initial use of your revised code this looks like it did the trick–thanks!

  129. David Stiller Says:

    nathan,

    Sure thing!

  130. Arthur Says:

    Now here is an odd problem I have…
    I have an as2 class in which I need to delay a function call.

    public function showImageAt(num:Number):Void
    {
    // some code

    var interval:Number = setInterval(
    function():Void {
    trace(”working”); // works
    test(); // doesnt work
    clearInterval(interval);
    },
    500
    );
    }

    private function aaa():Void
    {
    trace(”aaaaaaa”);
    }

    so my function aaa() never get called… any ideas.. anyone?

  131. Arthur Says:

    sorry the previous call would be to aaa();

    i have the same issue as listed above.

  132. David Stiller Says:

    Arthur,

    What you’re seeing is an issue of scope. Your aaa() function is defined as a method of the class, but the function literal inside your showImageAt() function is scoped to showImageAt() — which basically means that setInterval() can’t find aaa() because it can’t see the other class methods from its current point of view.

    Use the optional scope parameter in setInterval() to tell it where to look:

    interval = setInterval(
      this,
      "delayedCall",
      num
    );

    In this context, this points to the class, so setInterval’s scope is re-routed to where it can actually see aaa(). Notice that the function, now in the second slot, is now a named function, referred to as a string. This means you’ll have to write a new function in your class called delayedCall():

    private function():Void {
      aaa();
      clearInterval(interval);
    }

    Note, also, that interval is no longer scoped to your showImageAt() method, either. You’ll have to declare that as one of your class properties so that it’s accessible from anywhere in the class.

    Finally, I think you probably want to replace that 500 with num, so that the showImageAt() method allows the delay to be configurable, right?

  133. Gokul Says:

    Thnx for the script, came very handy :)

  134. aldw Says:

    Much appreciation for the script ;)

    Found this blog with google.

    ..aldw

  135. David Stiller Says:

    To Gokul …

    Sure thing!

    To aldw …

    Glad to help. :)

  136. Lance Says:

    Hi David,

    Thanks for this excellent and simple tutorial! I’ve been using Flash for years but as a designer, coding is not something I pick up easily…

    Thanks!

    Lance

  137. David Stiller Says:

    Lance,

    Glad to hear that. :) Thanks for mentioning it!

  138. Eugen S Says:

    Thanks, u’ve been really helpful !

  139. Wendy Says:

    I had been searching for this snippet of code for literally HOURS!!! I was so frustrated - Thank you! I finally found your code via a Google search after trying several fancier scripts that just wouldn’t work for some reason. Thank you!!!

    Wendy

  140. David Stiller Says:

    To Eugen S …

    Glad to hear it!

    To Wendy …

    You’re welcome. :)

  141. Ryan Says:

    Thanks so much David! I read your help to Lucas way back from June 2006 to clear the interval when a button is pressed! Your hands on help, expertise, and ability to convey Actionscript lessons in an easy-to-understand way are greatly appreciated!!!

    Thnx again!

  142. David Stiller Says:

    Ryan,

    You’re very welcome. Glad I could help!

  143. Alex Says:

    Wow! this is some really useful info! Thanks so much david i really appreciate it!

  144. Neilando Says:

    Hi. I am a total novice at AS. I am trying to get your code to work, with a small change. I want to execute your code on a button click, so that when the button is clicked, the timeline goes to a certain frame, pauses, then goes onto another specidic frameafter it has unpaused. How can i do that?

    on (release) {
    gotoAndPlay(10);
    var interval:Number = setInterval(
    function():Void {
    play();
    clearInterval(interval);
    },
    2000
    );
    }

    Where do i add the code to restart the timeline from a specific frame??

  145. David Stiller Says:

    To Alex …

    Thanks!

    To Neilando …

    If you’re using on(), then your code has to be attached directly to the button. I recommend you go with a keyframe version of the same event handler, described in the “museum pieces” entry of this blog. Regardless, the following should work, based on your description (this assumes a button with the instance name myButton):

    stop();
    var interval:Number;
    myButton.onRelease = function():Void {
      gotoAndStop(10);
      interval = setInterval(
        function():Void {
          clearInterval(interval);
          gotoAndStop(20);
        },
        2000
      );
    }

    That looks a bit messy, but all it does is send the playhead immediately to frame 10, where it stops, then waits 2 seconds before sending it to frame 20, where it stops again.

    Does that make sense? All of the above code would go into whatever frame (I’m assuming frame 1) the button appears in.

  146. Kelley Says:

    This appears to be the answer I am looking for - the proper code to attach to a button which, when clicked, causes the timeline to pause - however, I want to pause on the CURRENT frame, and then on a click, UNPAUSE on the same frame. How do I tell the program to recognize whatever the current frame is?

  147. Kelley Says:

    No, I just tried this and it does not work with my situation - I am trying to pause the currently running Movie Clip with a pause button, and then start the Movie Clip playing again using a play button. I don’t want timed pauses… the pause is indefinite, it is user defined. This is the code I tried which did not work, attached to ‘pauseBtn’ which resides in the first frame of a pausePlay MovieClip (frame two is where playBtn resides):

    on (release) {
    pauseBtn.onRelease = function():Void {
    //move to the next frame for the play button
    gotoAndPlay(2);

    //pause the MovieClip on the current frame
    gotoAndStop(”_parent.currentFrame”, 1);
    interval = setInterval(function():Void{
    clearInterval(interval);
    gotoAndStop(”_parent.currentFrame”, 1);
    } );
    }
    }

    How do you utilize this method to pause a MovieClip in the current frame, and then start again from that frame?

    Kelley

  148. Pastor Says:

    Thanks, this script has been mighty helpful.

    More power to you man!

  149. Ab Says:

    David,

    Spent ages looking for that snippet of knowledge.

    Cheers Dave!

  150. ilike2flash Says:

    Thanks, very helpful.

  151. Sarjon Says:

    very helpful indeed

  152. UzuNarU Says:

    Site is down, but will be back shortly!

    Anyways I really wanted to thank you for this piece of code, I spent a good 30 minutes trying to find this code for AS 2.0. It’s been a little while since worked with Flash. Is it possible to incorporate this into a button or would I justt make the button go to the frame and the AS in that frames AS layer will automatically activate?

    Thanks Again David

  153. popflier Says:

    I spent hours looking for a solution for this online via tutorials, forums, etc… and nothing I tried worked until I came across your blog. I don’t quite have it working right in AS3, but I’ll keep working with it and adjusting. I saw someone else on another site was looking for this solution too. I will send them to your page.

    Many thanks!
    Nicole

  154. Digitalex Says:

    secrets are never complex, they are profoundly simple, that’s why they are kept secret!

    thanks David

    btw this is the first blog i’ve ever been inspired to partake in! and the most positive one

  155. sandy g Says:

    David…

    Thank you…thank you…of course, it worked first time, every time!
    Your style of explaining things is superb!!
    I was able to make the connection between animated gifs and flash pausing finally. Now if I could get my movie to pause at the end and just loop 3 times, I would be ecstatic. Help.

    Your code on looping was fantastic and kept me from insanity. Now I need to put them together.

    I know the lightbulb is coming on soon, lol. Thank you again.

  156. David Stiller Says:

    To Kelley …

    I am trying to pause the currently running Movie Clip with a pause button, and then start the Movie Clip playing again using a play button. I don’t want timed pauses… the pause is indefinite, it is user defined.

    Gotcha. :) Fortunately, for this sort of pausing, where a timer isn’t needed, the code is actually much simpler!

    One of the issues with your code example is that you were combining the on() and dot notation approaches for your pauseBtn event handler. The cleanest way I can think of to do this, assuming you have a pause button, a play button, and a content movie clip, is the following:

    pauseBtn.onRelease = function:Void {
      contentClip.stop();
    };
    
    playBtn.onRelease = function():Void {
      contentClip.play();
    };

    In this situation, you don’t have to reference the content clip’s current frame, because when you invoke MovieClip.stop() on it, it’ll simply stop where it is, and be ready to resume later from that same frame.

    Let me know if this makes senese (or doesn’t)! :)

    To Pastor, Ab, ilike2flash, Sarjon …

    Thanks!

    To UzuNarU …

    Is it possible to incorporate this into a button

    I’m guessing you’d want a pause button always present, where the user could — at any time — halt the action for x-number of seconds? This would do it, assuming your pause button has the instance name pauseBtn, and that it sits in the same timeline as the following code.

    var interval:Number;
    
    pauseBtn.onRelease = pause;
    
    function pause():Void {
      this._parent.stop();
      interval = setInterval(resume, 2000);
    };
    function resume():Void {
      play();
      clearInterval(interval);
    };

    Note that the object reference for the main timeline is different for both custom functions. In the pause() function, the reference is this._parent.stop();, because in AS2, this function’s point of view (its scope) belongs to the pauseBtn button, to whose Button.onRelease event it’s assigned. In the resume() function, no reference prefix is necessary — simply play() will do — because the scope of this function belongs to the main timeline (where the code is written).

    To Nicole …

    Glad to hear it; thanks!

    To Digitalex …

    btw this is the first blog i’ve ever been inspired to partake in! and the most positive one

    Most positive is a high compliment! Thank you!

    To sandy …

    Thank you…thank you…of course, it worked first time, every time!
    Your style of explaining things is superb!!

    So glad to hear that. Glad it’s working out for you! When the light bulb finally does light, it really is a good feeling!

  157. Pram Says:

    Hi David Stiller,
    I need your help !!!!
    I am developing a flash based presentation application for

    kiosk which need to reset or go to fist frame every time

    after 30 second when its not in use (as many people leave

    kiosk in middle of application which need to reset

    automatically after 30 sec)

    Please let me know the code for automatic reset or go to

    stop in first frame of application in flash.

    Waiting for your reply.
    Thanks,
    pram

  158. Michael Says:

    Hi thanks for your post, I have a question.

    I want a banner which pauses on an image for about 10 seconds, then moves to the next image for 10 seconds, and so on. there will be buttons so you can click to view one specific image (like the news section of this site: http://www.essendonfc.com.au/main.asp).

    I’ve made it so the movie loops by itself, but when you click a button to view one of the other images, it loops back to the start frame but is meant to wait for another 10 seconds on that image, but for some reason it only waits 7-8 seconds (or sometimes not at all).

    Could you take a look and tell me where I’ve gone wrong? The link to the SWF is here (http://www.conceptmedia.com.au/banner.swf) and the link to the flash file is here (http://www.conceptmedia.com.au/banner.fla).

Leave a Reply