How to Pause a Timeline (AS2)
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.
setInterval(functionReference, timeInterval);setInterval(functionReference, 2000);setInterval(function():Void {}, 2000);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.
April 7th, 2006 at 12:57 pm
stop(); my beating heart… You’re the man, Stillonius
April 11th, 2006 at 12:56 am
stop();
setTimeout(function () { play();}, 100)
It works OK in as2.0+!
April 11th, 2006 at 3:14 am
what if you wanted to scope the id to a mc or object?
April 11th, 2006 at 6:37 am
木頭,
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 casesetInterval()would keep triggeringplay()for the rest of the movie. That may or may not be harmful. If you had a handful of otherstop()functions strewn about the timeline, the loopingplay()trigger might coincidentally interfere with those.April 27th, 2006 at 11:36 am
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?
April 27th, 2006 at 11:53 am
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/
May 26th, 2006 at 5:21 pm
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
May 26th, 2006 at 7:08 pm
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?
June 4th, 2006 at 5:13 am
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.
June 4th, 2006 at 7:00 pm
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
idvariables aren’t getting cleared byclearInterval(). 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.
June 10th, 2006 at 5:39 am
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
June 10th, 2006 at 1:47 pm
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
:Numbersuffix in line 2 of my code or b) change your publish settings to publish for ActionScript 2.0. That solves it.June 11th, 2006 at 9:34 am
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.
June 20th, 2006 at 1:00 pm
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
June 21st, 2006 at 1:15 am
Lucas,
If the timing goes batty after a number of frames, it’s because your interval ID — the variable I named
intervalabove — isn’t being recognized byclearInterval(). Addtrace(interval);just before theplay();function in the sample code above. See what you get in the Output panel. If it’s something other thanundefined, 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.
June 21st, 2006 at 5:22 pm
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?
Thanks, Lucas
June 21st, 2006 at 7:11 pm
Lucas,
It sure would; but
trace()allows you to look under the hood, so to speak. And since your Output panel shows sequential numbering instead ofundefined, I guess I have to eat my hat.Do you have this same code — not counting
trace()— on each of your 30 keyframes?June 22nd, 2006 at 1:22 pm
David,
I have the same code on each of the 30 keyframes, including trace()…
Thanks for your continued effort! It’s appreciated. Lucas
June 22nd, 2006 at 7:00 pm
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:
First, you stop the timeline. Next, you declare a new variable, thanks to that
varstatement, and you set your variable to whatever value comes back from thatsetInterval()function. Since this is your first interval, the return value happens to be1. Fine, that’s good and stored.setInterval()will triggerplay()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.
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 …
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 fromsetInterval(). 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 thenclearInterval(interval). What’s the value ofintervalagain? 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.Until you hit frame 2, the value of
intervalis still1, so that first interval will be propertly cleared. Make sense?July 5th, 2006 at 4:38 pm
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
July 6th, 2006 at 1:56 pm
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()andgotoAndStop()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.”
July 14th, 2006 at 2:43 am
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
July 15th, 2006 at 8:04 am
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.
July 25th, 2006 at 10:15 pm
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.
July 26th, 2006 at 8:42 am
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.
August 27th, 2006 at 11:50 pm
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);
}
};
August 28th, 2006 at 7:59 am
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.onEnterFrameevent — in Flash 5, you would have had to useonClipEvent(enterFrame)— but it might also have been the strong typing (:Number), which is only available to ActionScript 2.0.September 19th, 2006 at 10:54 am
hey man you still got the skills. Stilla in Manilla
October 20th, 2006 at 2:12 pm
I’ve searched the web for a script that is easy to understand and that works.
Thanks for keeping it simple.
Regards,
October 20th, 2006 at 3:26 pm
Sure thing, Karen! Glad to help.
November 7th, 2006 at 6:21 pm
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
November 9th, 2006 at 3:23 pm
Jake,
I sounds like your
clearInterval()isn’t managing to close thesetInterval()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 usesclearInterval(), along withid, or whatever variable you’re using to capture the return value ofsetInterval(), to keep theplay()action from occurring.November 13th, 2006 at 5:46 am
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
November 13th, 2006 at 10:04 am
Andy,
Careful pathing will take care of that for you. Rather than using the global
play()function, use its cousinMovieClip.play()method, instead. The only gotcha is that the globalthisproperty won’t refer to the desired movie clip’s timeline without extra help, such as theDelegateclass available since the Flash MX 2004 7.2 minor revision.November 18th, 2006 at 11:13 am
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
November 20th, 2006 at 9:49 am
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.
November 21st, 2006 at 6:55 pm
Thanks very much for the Pause script. I’m only a newbie and yours is the simplest I’ve found.
November 25th, 2006 at 11:55 am
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!!!!!!
November 25th, 2006 at 12:29 pm
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!
November 25th, 2006 at 2:07 pm
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!!!
November 27th, 2006 at 3:02 am
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.
December 14th, 2006 at 2:48 pm
Thanks, David,
That was *just* the little snippet of code that I needed!
-Ryan
December 21st, 2006 at 1:07 pm
This script has been really helpful. Easy to understand and to use. Thank you.
January 15th, 2007 at 9:43 am
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
January 15th, 2007 at 10:10 am
Alex,
By declaring your variable inside the
wait()function, you’re scoping the variable to that function alone. Nothing outside thewait()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.
… which means that ActionScript outside that function could also clear the interval
interval. Keep in mind, you’re going to see incremental values ofintervalevery time thewait()function is called — that’s the waysetInterval()works. Until you restart your SWF, Flash will not restart from 1.January 15th, 2007 at 11:41 am
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!
January 16th, 2007 at 5:54 am
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
January 16th, 2007 at 6:20 am
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
January 16th, 2007 at 7:29 am
Alex,
I can see more clearly now what you’re trying to accomplish. In the case of external SWF files, your ActionScript here …
… runs the variable
intervalthroughclearInterval()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
intervalvariable specifically. You can either do that, as you’ve discovered, by calling a function in the loaded SWF …… or simply like this:
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.
January 30th, 2007 at 5:49 am
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
January 30th, 2007 at 7:53 am
Alex,
The
setInterval()andsetTimeout()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 theMovieClipLoaderclass, as it provides useful events by which you can monitor load progress and completion.January 30th, 2007 at 4:19 pm
Thanks!
February 19th, 2007 at 12:20 am
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
February 19th, 2007 at 12:24 pm
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 thesetInterval()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:Numberpart)? 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.February 20th, 2007 at 7:45 pm
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
February 20th, 2007 at 8:34 pm
Ann,
You’re welcome!
March 21st, 2007 at 10:39 am
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
:)
March 23rd, 2007 at 10:25 am
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
March 27th, 2007 at 5:36 am
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
March 27th, 2007 at 8:13 am
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
MovieClipLoaderclass, rather thansetInterval().March 27th, 2007 at 10:03 am
sharon,
Since you’re using the
Tweenclass, your best bet is to use theonMotionFinishedevent, as you did earlier in the code. However, this only makes sense ifemail_mcis an instance of theTweenclass, and I’m not at all sure that it is.If
email_mcis aMovieClipinstance, 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 withsetInterval()to repeatedly check if the value ofemail_mc’sMovieClip._currentframeproperty has reached the value of itsMovieClip._totalframesproperty.Does that help?
March 28th, 2007 at 3:57 am
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
March 28th, 2007 at 9:06 am
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.onLoadCompleteevent 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.March 28th, 2007 at 7:37 pm
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
April 1st, 2007 at 11:57 am
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 theplay()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.
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.
April 2nd, 2007 at 1:43 pm
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.
April 2nd, 2007 at 2:02 pm
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
MovieClipclass. 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.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!April 26th, 2007 at 4:07 am
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
May 1st, 2007 at 7:49 pm
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!
May 1st, 2007 at 8:20 pm
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
thisto theKeyclass, you’re going to need a genericObjectto act as your “liaison” for theonKeyDownevent. Give this article a look and see if it helps you out; if not, I’ll tell you the answer, quick-like.May 8th, 2007 at 9:22 pm
Alex,
You’re pretty close.
In a situation like this, I would probably call that custom
wait()function from theonLoadCompleteevent handler. (Note: Check theMovieClipLoaderclass entry for the difference between theonLoadCompleteandonLoadInitevents, in case you want to use the latter.)That way, once each image loads, your
slowFadeIn()function is called,progress1’s_visibleproperty is set tofalse, and finally … you’d invoke thatwait()function — which would, in turn, callloadRandom()…May 31st, 2007 at 11:09 am
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.
May 31st, 2007 at 12:38 pm
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.
June 1st, 2007 at 4:51 pm
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.
June 5th, 2007 at 1:08 pm
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
June 7th, 2007 at 10:20 am
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
June 7th, 2007 at 10:28 am
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
June 7th, 2007 at 10:46 am
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
June 7th, 2007 at 10:53 am
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:Numberwasn’t registering because of the:Numberin that version of the language, so there really wasn’t anintervalvariable to reference in theclearInterval()function call. Because of that, theplay()keeps getting called every five seconds. For ActionScript 1.0 SWFs, drop the:Numberand it works out fine.June 16th, 2007 at 8:57 pm
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
June 18th, 2007 at 8:31 am
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.
August 23rd, 2007 at 2:04 pm
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.
August 27th, 2007 at 12:58 pm
Eric,
See this new article here.
August 30th, 2007 at 11:51 am
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
August 30th, 2007 at 12:09 pm
Steve,
Thanks!
September 15th, 2007 at 4:06 pm
setTimeout(); works for me in AS3, but not setInterval();
Thanks, 木頭
September 19th, 2007 at 3:25 pm
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
September 22nd, 2007 at 3:18 pm
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();
September 22nd, 2007 at 7:43 pm
To io …
Although the
setTimeout()andsetInterval()functions are still available in ActionScript 3.0, they’ve been re-routed to theflash.utilspackage; in addition, the ActionScript 3.0 Language Reference strongly recommends theTimerclass instead: “Although you can use this method, it will generate a compiler warning. Instead of using thesetInterval()method, consider creating aTimerobject, with the specified interval, using 0 as therepeatCountparameter (which sets the timer to repeat indefinitely).” sourceTo 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 andplay()on the Play button.September 26th, 2007 at 10:06 pm
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
September 27th, 2007 at 1:23 am
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
September 27th, 2007 at 8:12 am
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.)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().The above would go in frame 1. Note, as before, that the
pauseIntvariable is declared at this point, which ensures that later references to it point to the same variable (in the original article, this wasinterval, but it doesn’t matter what you call the variable).In later frames, you wouldn’t have to use
varto re-declare the variable. On any frame that needs pausing, use:… 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 thestop()function on that frame.September 27th, 2007 at 11:15 am
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
September 27th, 2007 at 11:50 am
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 thesetInterval()code orstop().The code in your bullet point 3 should go in frame 1 of your scripts layer, along with the button event handlers.
September 27th, 2007 at 12:51 pm
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
September 27th, 2007 at 12:52 pm
BTW You rock so HARD!!!!!
Edub9
September 27th, 2007 at 3:50 pm
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 (thenMovieClip.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: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..inloop, in cahoots with the array access operator, for that (see “How to Reference Objects Dynamically” for more detail).September 27th, 2007 at 4:09 pm
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();
September 27th, 2007 at 4:25 pm
Edub9,
We’ve come full circle!
Okay, here’s my understanding:
So far, so good. One button that either pauses or plays, as needed.
Where are these keyframes? In the main timeline? What happened to the 27 animated movie clips?
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
pauseCountequals 300 (the passed in value,pc), then …clearInterval(pauseInt);play();
… kill the
setInterval()loop and play; otherwise …_root.pauseCount++;… increase the value of
pauseCountby 1. So when the playhead enters the frame that contains this code, the custompause()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, becausesetInterval()is being asked to repeatedly trigger thepause()function every zero milliseconds. Over all, it’s much less complex (which is usually good) to simply use this: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..inloop and invokeMovieClip.stop()orMovieClip.play()on them.September 27th, 2007 at 5:37 pm
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
October 2nd, 2007 at 12:59 pm
[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 thesetInterval()return value (intervalandpauseInt), which actually needed to be the same — so he was callingclearInterval()from the button event handlers on a different (non-existent) variable from the one returned bysetInterval().With these corrections, the file worked as expected.
October 4th, 2007 at 1:31 am
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
October 4th, 2007 at 8:13 am
Irina,
For better or worse, Flash keeps no record of the apps it launches via the
execcommand forfscommand(). 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.
October 5th, 2007 at 9:45 pm
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
October 8th, 2007 at 4:00 am
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?
October 8th, 2007 at 8:29 am
To Edub9 …
Glad everything’s working!
To Charlie …
In ActionScript 3.0, the term
Voidhas been changed to the lowercasevoid, but revising that isn’t going to be your best bet, in this case. In AS3, the recommended approach toward timed triggering is no longersetInterval()orsetTimeout(); instead, you’ll want to use theTimerclass, 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.October 9th, 2007 at 12:53 pm
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!!!
October 9th, 2007 at 2:04 pm
Mary Anne,
So glad I could help! I hope you get more out of the rest of the blog.
October 9th, 2007 at 4:52 pm
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
October 9th, 2007 at 9:22 pm
Emanuel,
The
setInterval()function might be causing your scope issues. Are you using the alternative approach tosetInterval()(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 namedmc. Check it out:October 10th, 2007 at 4:32 pm
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.
October 10th, 2007 at 5:32 pm
Emanuel,
If you’re talking about the
MovieClip.play()method, you’ll find thatplay()doesn’t accept any parameters — butgotoAndPlay()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
myClipto frame 10 of its own timeline.October 11th, 2007 at 7:42 am
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
};
October 15th, 2007 at 8:14 pm
Emanuel,
There’s quite a bit going on here that is completely unknown to me, such as your variables
sliderAmountandplayWhenReleased, as well as theonMouseMoveandonEnterFramestuff (where isactionPackdeclared?).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.
October 16th, 2007 at 2:24 pm
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?
October 16th, 2007 at 3:02 pm
Emanuel,
I mentioned
setInterval()because your first post mentioned it, and you observed thatsetInterval()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 needsetInterval().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, andMovieClip.play()to resume it. If the loaded content happens to use thesetInterval()code in its own timeline, then the mechanism that controls it — that scrubs it — must cancel the loaded content’s interval by invokingclearInterval()on the variable inside the loaded content that holds the return value ofsetInterval().Am I getting closer to what you need?
November 3rd, 2007 at 1:42 am
U did a good job
thanx…
November 3rd, 2007 at 10:55 am
virendra,
Thanks!
November 9th, 2007 at 3:22 am
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!
November 9th, 2007 at 9:11 am
James,
Super! Cheers right back.
November 15th, 2007 at 4:16 pm
Thanks for posting this; I found it very helpful.
November 26th, 2007 at 4:10 pm
thanks for this! it’s just what i needed.
November 27th, 2007 at 12:32 am
To Jimmy …
You’re welcome!
To rob …
Glad to hear it.
January 18th, 2008 at 10:56 am
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
January 22nd, 2008 at 9:30 pm
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?
January 29th, 2008 at 7:25 pm
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!
January 29th, 2008 at 8:18 pm
nathan,
Sure thing, bro.
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
onRollOverevent handler, which sends the timeline to frame 4. At this point, the user’s mouse is overbtn1. The user could sit there for half an hour, and nothing would happen, because theonRollOverhandler 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, theonRollOutevent is handled. This handler does the following:intervalStatusis"open", the timeline is sent to frame 3The only thing that changes
intervalStatusto something other than"open"is theonReleaseevent 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 whenintervalStatusisn’t"open".Now, you’re saying the
onReleasehandler somehow erases theonRollOuthandler, which doesn’t seem right. I think that’s actually going on is that you’re declaring two differentintervalStatusvariables. One is declared in the main timeline and the other is specifically scoped to thebtn1instance. Drop thevarand:Stringinside theonReleasehandler and see if that helps. I would probably declare theintervalvariable outside of the function, as well:Note that I changed your
elseclause a bit.I’m not sure the above is what you need, but worth a shot.
January 30th, 2008 at 2:56 pm
hey david,
thanks for fixing this. from my initial use of your revised code this looks like it did the trick–thanks!
January 30th, 2008 at 4:59 pm
nathan,
Sure thing!
February 7th, 2008 at 10:52 am
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?
February 7th, 2008 at 10:53 am
sorry the previous call would be to aaa();
i have the same issue as listed above.
February 7th, 2008 at 11:07 am
Arthur,
What yo