ActionScript.org Flash, Flex and ActionScript Resources - http://www.actionscript.org/resources
Timer Controlled Events
http://www.actionscript.org/resources/articles/103/1/Timer-Controlled-Events/Page1.html
Jesse Stratford
Jesse lives and works in Melbourne Australia. He is the Cofounder of http://ActionScript.org. A Flash enthusiast, teacher, author, freelancer and speaker Jesse's main focus nowadays is managing http://ActionScript.org, but he enjoys participating actively in community and the wider Flash scene when he has time. 
By Jesse Stratford
Published on September 9, 2005
 
Tutorial details:
Written by: Jesse Stratford [email:jessestratford@actionscript.org]
Time: 20 minutes
Difficulty Level: Intermediate
Requirements: Flash 4 or 5, (Flash 4 code will be significantly different).
Topics Covered: How to perform various events every X seconds.
Assumed knowledge: Variables, Paths, MovieClip Actions, Conditional Statements, basic math.

Page 1 of 2
Tutorial details:
Written by: Jesse Stratford [email:jessestratford@actionscript.org]
Time: 20 minutes
Difficulty Level: Intermediate
Requirements: Flash 4 or 5, (Flash 4 code will be significantly different).
Topics Covered: How to perform various events every X seconds.
Assumed knowledge: Variables, Paths, MovieClip Actions, Conditional Statements, basic math.


This face will duplicate at a random point, every two seconds, until there are 20 faces, then stop.
Download the source here.

The inspiration behind this tutorial is two fold. Firstly, it's generally useful to know how to do, and secondly it will stop us having to explain how every time someone wants to perform such an action. Recently there's been a lot of requests along the lines of "I want to do <some event> every <random number of> second until <some condition is met>". Now in Flash 4 most people achieved this using very long MovieClips with lots of empty frames, or the more sophisticated used GetTimer. In Flash 5 we have all sorts of fancy controls over the time elements and I still prefer the getTimer method. Call me old fashioned if you will.

Let's get into it! There's not really much of a need for an intro to this tutorial so I'll just show you the code and explain how it works, shall I?

Define this variable in Frame 1 of your movie:

[as]_root.wait = 10;[/as]

This 'wait' variable is the number of second to wait between each event. It must be an integer greater than 1! For those of you who don't speak Math, that means a whole number, so no decimal points or fractions.

Create a controller MC (just a blank MC which will sit off the stage somewhere) and add these actions:

[as]onClipEvent (enterFrame) {
 if (_root.delay) {
  if (Math.floor(getTimer()/1000) == _root.lastTime+1) {
   _root.delay = false;
  }
 } else if (Math.floor(getTimer()/1000) == _root.lastTime+_root.wait) {
  _root.lastTime = Math.floor(getTimer()/1000);
  _root.delay = true;
  // custom actions go here
 }
}[/as]

What it does (line by line):

  1. Perform these actions every frame. So if your frame rate is 12fps, these actions will be performed 12 times per second while the movie is playing.
  2. If the variable delay on the _root level is True, then;
  3. If the current time in seconds is one second greater than the last time logged, where;
    • Math.floor() - Rounds the number in the brackets down to the nearest whole number.
    • getTimer() - The time in thousandths (1/1000) of seconds since the movie began playing. Hence getTimer()/1000 is the time in whole seconds since the movie began playing.
    • _root.lastTime - A root level variable which stores the time at which we last executed out events. On the first run-through this code, the events have not been executed at all so this variable is equal to 0.
  4. Set the variable delay on the _root level to False.
  5. End If
  6. (Else clause for Line 1's If statement) - If the current time in seconds is equal to the last time logged plus the time interval to wait, where;
    • Math.floor() - As above, see 3.i.
    • getTimer()/1000 - As above, see 3.ii.
    • _root.lastTime - As above, see 3.iii.
    • _root.wait - A root level variable which stores the time interval to wait between actions.
  7. Set the variable lastTime on the root level to the current time.
  8. Set the variable delay on the root level to True.
  9. Comment. This is where you will insert your own scripts which perform the actions you wish to perform every X seconds.
  10. End If
  11. End onClipEvent.

Don't worry, I explain it a bit better over the page ...


Page 2 of 2

Now that run-down is terribly in-depth so let me break it down a bit. You start with no variables so your delay variable is not true and your lastTime variable has no value. Therefore the delay == true If clause is skipped and the computer checks if the current time is equal to lastTime ( zero ) plus the wait variable. If it isn't it does nothing and the whole process is performed again, every frame, until the current time is equal to the specified waiting time.
Now the actions within the Else If are carried out. The lastTime variable is set to the current time, and the delay variable is set to true. Then all your custom actions (which you insert at line 9) are carried out also.
The delay variable is there because this loop is run through many times per second, and during that one second, the Else If clause is always true, thus if your frame rate is 12 fps, you would get these actions executing 12 times every time, instead of just once. So I added the delay variable which is true once the actions have been performed once. It is reset to false 1 second later. This is why your wait time must be greater than 1 second!
The lastTime variable just keeps being incremented to indicate the time when we last perform the actions. It's basically just used to keep track of how long until we need to perform the actions again.

So you can add any actions you want in at Line 9 (note you can add multiple lines of code) and this script will run that code every X seconds. You can also add an extra If to your own code with a counter variable if you only want to perform a certain action say 10 times.

Finally, this code assumes that your actions begin at the beginning of the movie. If you don't wish to start repeating actions instantaneously when the movie starts, you will need to trigger this code using a button or the like. You will also need to take into account the value of getTimer() when the user clicks the button, as the code above assumes it is zero. It's not hard to do, all you have to do is create another variable which remember at what time your user began the wait loop.

If you have any problems post your questions on the forums please and someone will answer them if they can.

Good luck!

Jesse Stratford [email:jessestratford@actionscript.org] is the Co-Master of ActionScript.org and a freelance Flash developer and teacher. He is based in Australia and enjoys all things Flash.

NB: If you have comments or feedback please feel free to email me, but please do not email me Flash questions; the forums are provided for that purpose and you will get a faster answer by posting you question there.

If you have found this tutorial helpful, I hope that you will take 30 seconds to visit The Hunger Site where, with just one click you can make a free donation of food to a starving person in a third-world country. We do not benefit financially from this action; it is purely an act of charity.
This tutorial is protected by International Intellectual Property Rights laws and may not be reproduced or redistributed in full or part, without the prior written consent of the author. Unauthorized reproduction of this tutorial or its contents may result in prosecution. I've worked hard on this tutorial, please don't steal it.