Countdown in Style With an Airport Terminal Timer

Countdown in Style With an Airport Terminal Timer

Tutorial Details
  • Difficulty: Intermediate
  • Program: Flash CS3 or above
  • Estimated Completion Time: 60 mins

Twice a month, we revisit some of our readers’ favorite posts from throughout the history of Activetuts+. This tutorial was first published in May, 2010.

In this tutorial we’ll make a reusable countdown timer with a dynamic target date that can be set via XML. We’ll animate the numbers flipping down in the style of an old airport or train station status board. We’ll cover code, graphics creation and animation.


Step 1: Set Up Your Flash File

Create a new Flash file (Actionscript 3) with these settings: 500×300, black background, and 30 fps.

Flash file setup

Step 2: Create the digit_bottom MovieClip

Create a new MovieClip called ‘digit_bottom’ and draw a rounded rectangle inside it approximately 36px wide by 50px tall. (A quick way to draw a rectangle with precise dimensions is to select the rectangle tool and Alt-click on the stage.)

Give the rectangle a gradient fill from #111111 (top) to #333333 (bottom) and a 2 px outline colored #333333.

Background image or animation

Step 3: Position the Rectangle

Position the rectangle so that the registration point of the MovieClip (the little ‘+’) is exactly halfway between the top and bottom and the left edge. If you made your rectangle 50px tall, then the y value should be -25.

Rectangle Properties

Step 4: Add the Number

Create a new layer and add a dynamic text field called ‘t_num’. Choose a font that has an airport or train station feel to it (like Helvetica, DIN, or Interstate). I’m using Helvetica Bold.

Set the Paragraph Format to centered, and remember to embed the fonts for the numbers 0–9.

Position the text field so it’s centered on the background rectangle.

Number text field

We’re going to be using this MovieClip as the base for another graphic, so take a moment to make sure it looks good.


Step 5: Add a Mask

Create a new layer on the timeline of the digit_bottom MovieClip and call it ‘mask’. Copy the rounded rectangle and Paste in Place on the mask layer (Edit > Paste in Place, or Command-Shift-V).

Select the top half of the mask rectangle and delete it.

Right-click the mask layer, choose Mask and make sure that it is masking all of the layers below it.

Create the Mask

Step 6: Create the digit_top MovieClip

Go into the Library, duplicate the digit_bottom MovieClip and name the new copy ‘digit_top’.

This MovieClip will be virtually identical to the digit_bottom clip, except the mask will be showing the top half of the graphics instead of the bottom.

Delete the graphics currently on the mask layer. Copy the rounded rectangle and again Paste in Place on the mask layer. This time select the bottom half and delete it.

The only other adjustment you might want to make here is to adjust the color of the text and the shading of the background rounded rectangle. I made the graphics in my digit_top clip a bit darker to simulate light coming from the top.

digit_top and digit_bottom clips

Step 7: Create the Digit MovieClip

Create a new MovieClip named ‘Digit’. Drag in the digit_top and digit_bottom MovieClips and position them both at 0,0. Give them the instance names ‘top1′ and ‘bottom1′.

Now copy both of the MovieClips (digit_top and digit_bottom), create a new layer, and Paste in Place a copy of each. Name the new copies ‘top2′ and ‘bottom2′.

You should now have 4 MovieClips inside your Digit MovieClip: 2 copies of digit_top and 2 copies of digit_bottom. I’ll explain why we’re setting it up like this in the next step.


Step 8: Animation Strategy

We have to do a bit of animation trickery to get the flipping numbers effect we want. Take a look at the diagram below of our Digit MovieClip (I’m rendering it in 3D just so you can see the layering more easily):

Digit Animation Diagram

Animation Step 1:

We start out with the bottom2 clip flipped upside down (using the scaleY property) and placed behind the top2 clip. At this point the 2 clips that are visible are top2 and bottom1. The numbers on these two clips correspond to each other, so they form a complete digit.

Animation Step 2:

Now we flip down the top2 clip to the center of the digit. At this point scaleY will be zero, so the clip won’t be visible. At the same time, we’re also flipping down the bottom2 clip, but this one we’ll flip all the way to the bottom. Since it’s behind top2, it won’t show until it flips past the halfway point. Now the 2 visible clips are top1 and bottom1. The numbers on these two clips don’t match, but that’s okay because this step only lasts for a brief moment.

Animation Step 3:

The top2 clip stays in the center as bottom2 continues to fall all the way down to the bottom. Once it’s in place the numbers on the visible clips (top1 and bottom2) again match to form a complete digit.

Animation Step 4:

At this point we’ll relayer and reset the positions of the 2 hidden clips to get ready for the next flip. Notice how the clips are in the same positions as Step 1, only reversed.


Step 9: Create the Clock MovieClip

Now that we have the individual Digit MovieClip set up, let’s build the clock.

Create a new MovieClip on the stage called ‘Clock’ with the instance name ‘clock’. Inside the new MovieClip place 9 copies of your Digit MovieClip; 2 for seconds, 2 for minutes, 2 for hours, and 3 for days. Give each digit an instance name. From left to right name them ‘digit0′, ‘digit1′, ‘digit2′, and so on.

Add some colons to separate the MovieClips and labels for each section. The design is up to you. I added a dark rounded rectangle as a background for my clock.

Lastly, add a dynamic text field called ‘t_date’. This is where we’ll show the target date the clock is counting down to. Remember to embed the font for this text field if you’re not using a system font.

Clock MovieClip

Step 10: Create the Digit Class

Create a new Actionscript file called ‘Digit.as’ and add this code to create the empty shell for the class:

package {

	import flash.display.MovieClip;

	public class Digit extends MovieClip {
		private const TOP:int = 0;
		private const BOTTOM:int = 1;

		private var _currentDigit:Array;
		private var _nextDigit:Array;
		private var _number:String = "0";

		// CONSTRUCTOR
		public function Digit() {
			_currentDigit = new Array( top1, bottom1 );
			_nextDigit = new Array( top2, bottom2 );

		}

	}

}

This doesn’t do much yet. We’ve got a couple of arrays to hold the 2 sets of digit_top and digit_bottom MovieClips. I’ve set up 2 constants, TOP and BOTTOM to help keep track of the top and bottom clips within those arrays. The _number variable will hold the digit that’s on display at any given time.

(Note: I’m using the underscore in my variable names to indicate private variables.)

Find your Digit MovieClip in the Library and assign this class to it in the Linkage settings.

Digit Class Linkage Settings

Step 11: Import the TweenLite Library

We’re going to be using the TweenLite library to animate our Digit MovieClip.

Download the AS3 version of the TweenLite library here.

Place the ‘com’ folder in the same directory as your main Flash file (or in your source path, if you’ve set up a different class path).

Add these two lines at the top of your Digit class, just below the MovieClip import:

import com.greensock.*
import com.greensock.easing.*

We’re barely going to scratch the surface of what TweenLite can do in this tutorial. For more information check out the TweenLite Documentation.


Step 12: Program the flipTo Animation

Add this function to your Digit class:

public function flipTo(num:String):void {
	_number = num;
	_nextDigit[TOP].t_num.text = num;
	_nextDigit[BOTTOM].t_num.text = num;

	// flip down the top of the digit to the halfway point
	TweenLite.to(_currentDigit[TOP], .15, {scaleY: 0, ease: Linear.easeNone});
	// flip the next digit bottom down
	TweenLite.to(_nextDigit[BOTTOM], .3, {scaleY:1, onComplete: flipComplete,  ease: Bounce.easeOut});
}

Here’s what’s happening, line by line:

  • This function accepts a String that will hold the digit we’ll be flipping to. The first line just sets our _number variable to hold that digit.
  • Next we set the text fields in the TOP and BOTTOM MovieClips in our _nextDigit array to display that same digit.
  • Then we use TweenLite to tween the scaleY property of the TOP MovieClip of the _currentDigit to 0. This gives the effect that it’s ‘falling’ toward the center of the digit.
  • The last line is another tween, this time animating the BOTTOM clip of the _nextDigit from the the top of the digit down to the bottom. Again we’re using the scaleY property to simulate this effect, but this time from -1 to 1. Since it’s tweening twice as far as the TOP clip, we give it twice the amount of time (.3 seconds instead of .15). When this tween finishes it will call a function called ‘flipComplete’. We’ll write that function in the next step.

Take another look at the diagram in Step 8 if you’re confused about the animation here.


Step 13: Add the flipComplete() Function

Add this function to the Digit class just below the flipTo function:

private function flipComplete():void {
	// swap digits
	var next:Array = _currentDigit;
	_currentDigit = _nextDigit;
	_nextDigit = next;

	// reset layering
	reset();
}

Once the flip animation completes we’ll run this function. It swaps the _currentDigit and _nextDigit arrays. After that’s done it calls a function named ‘reset’ to reset the clip layering and positions for the next flip. Let’s write that function now.


Step 14: Add the reset() Function

Add this function to the Digit class:

private function reset():void {
	addChild(_nextDigit[BOTTOM]);
	addChild(_currentDigit[TOP]);

	// flip up the next bottom to be behind the current top
	_nextDigit[BOTTOM].scaleY = -1;
	_nextDigit[TOP].scaleY = 1;
}

The first two lines in this function pop the _nextDigit BOTTOM and then the _currentDigit TOP to the top of the display list. I usually just use addChild() to do this because it requires less typing than using setChildIndex().

After the clips are re-layered, we set the scaleY properties so they’ll be ready for the next flip. This means changing _nextDigit[BOTTOM] from 1 to -1 and _nextDigit[TOP] from 0 to 1.

Again, check the diagram in Step 8 if you’re getting lost.


Step 15: Add to the Constructor

One thing we forgot to do is position the clips properly for the first flip animation. We can do that easily by adding a call to the reset function right in the Digit class constructor:

// CONSTRUCTOR
public function Digit() {
	_currentDigit = new Array( top1, bottom1 );
	_nextDigit = new Array ( top2, bottom2 );

	reset();
}

Step 16: Add the number() Function

One last thing we’ll need in our Digit class is a way to access the private _number variable from outside the class. We’ll add a simple accessor function:

public function get number():String {
	return _number;
}

Step 17: Create the Clock Class

Create a new ActionScript file named ‘Clock.as’. Paste in this code:

package {

	import flash.display.MovieClip;
	import flash.events.TimerEvent;
	import flash.media.Sound;
	import flash.utils.Timer;

	public class Clock extends MovieClip {
		private var _clockTimer:Timer;
		private var _targetDate:Date;

		// CONSTRUCTOR
		public function Clock() {

		}

	}

}

Not much here yet. Just importing some of the classes we’ll need. I also have a couple of private variables. _clockTimer will count down the seconds for us, and _targetDate will hold the date that we’re counting down to.


Step 18: Add the set() Function

Add this function to the Clock class just below the constructor:

// set the target date and start the countdown timer
public function set(date:Date):void {
	_targetDate = date;

	_clockTimer = new Timer(1000) // tick every second (1000 milliseconds)
	_clockTimer.addEventListener(TimerEvent.TIMER, update);
	_clockTimer.start();

	// display the target date above the clock
	t_date.text = _targetDate.toLocaleString().toUpperCase();

	// update the clock once here so it starts with the correct time
	update();
}

This is the function that we’ll use to set the target date for the clock. It accepts a date (of course) and assigns that to the _targetDate variable. It then instantiates our _clockTimer. The _clockTimer will call the update function once per second to update the digits.

After starting the timer, the function sets the t_date text with the target date. The toLocaleString() function ensures the date is displayed in the user’s local time zone.

The last line of this function calls update once to set the clock to the proper time. Otherwise it would display “000 00:00:00″ for one second until the first timer event.


Step 19: Add the update() Function

This function is a bit long because it’s where most of the work gets done. Add it to your Clock class:

private function update(e:TimerEvent = null):void {
	var now:Date = new Date(); // get the current time

	// find the difference (in ms) between the target and now
	var diff:Number = _targetDate.valueOf() - now.valueOf();
	if(diff <=0){
		// TIME'S UP!
		// do something cool here
		_clockTimer.stop();
		_clockTimer.removeEventListener(TimerEvent.TIMER, update);
		diff = 0;
	}

	// convert to seconds
	diff = Math.round(diff/1000);

	// number of days
	var days:int = Math.floor(diff/ (24 * 60 * 60));
	diff -= days*(24 * 60 * 60 );

	// number of hours
	var hours:int = Math.floor(diff / (60 * 60))
	diff -= hours*60 * 60;

	// number of minutes
	var min:int = Math.floor(diff/ 60);
	diff -= min*60;

	// seconds are all that remain
	var sec:int = diff;

	// create an array of strings to hold the number for each value
	var diffArr:Array = new Array(String(days), String(hours), String(min), String(sec));
	var diffString:String = ""
	var len:int = 3; // the first value (days) has 3 digits. All the rest have 2
	for each(var s:String in diffArr){
		// pad the string with a leading zero if needed
		while(s.length < len){
			s = "0"+s;
		}

		len = 2; // all the other values are 2 digits in length
		diffString += s; // add the padded string to the diffString
	}

	// go through each character in the diffString and set the corresponding digit
	for(var i:int = 0; i< diffString.length; i++){
		if(diffString.substr(i, 1) != this["digit"+i].number){
			this["digit"+i].flipTo(diffString.substr(i, 1));
		}
	}

}

This function accepts a TimerEvent as its parameter. The default value for this parameter is null. This allows us to call the function without sending a parameter, as we’re doing in the set function.

The first line of this function gets the current date and time as a Date object. Next, we find the difference between the current date and the target date (line 37). If the difference is 0 or less, then it’s past the target date, so we stop the _clockTimer (lines 38-44).

Since the difference in time between now and the target is calculated in milliseconds, we need to convert that into a nice readable display of days, hours, minutes, and seconds (lines 46-62). The math here is pretty simple as long as you know that there are 1000 milliseconds in a second, 60 seconds in a minute, 60 minutes in an hour and 24 hours in a day.

On line 65 we store all those values as elements in an array. Starting on line 68 we loop through each element and add it to a String of characters called ‘diffString’. While doing this we also add leading zeroes where necessary (line 71). So if our values for the clock were 30 days, 5 hours, 56 minutes, and 6 seconds the diffString would look like this: “030055606″.

The last thing this function does is loop through the characters in the diffString (using the charAt() method). For each character in the string we check to see if it’s different from the number currently displayed on the corresponding digit. This is easy because of the way we named our digit instances. If the number is not the same as the one currently displayed we tell that digit to flip to the number in the diffString.


Step 20: Add Sound

Find (or create) a good ticking sound that will play every time the clock updates. Import it into the Library of your Flash file and set the class name to ‘TickSound’ in the Linkage settings.

Tick Sound Linkage Settings

Add the _tickSound variable to the top of your Clock class just below the two other variables:

private var _clockTimer:Timer;
private var _targetDate:Date;
private var _tickSound:Sound = new TickSound();

And play the sound inside the update function:

_tickSound.play();

Step 21: Add the Main Document Class

Our countdown timer is complete, we just need some way to set the target date. Create a new Actionscript file called ‘Main.as’ with this code:

package {

	import flash.display.MovieClip;

	public class Main extends MovieClip {

		public function Main() {

			// set the target date for the clock
			var targetDate:Date = new Date();
			targetDate.setTime( Date.UTC(2010, 4, 28, 20, 00) );
			clock.set(targetDate);
		}
	}

}

All this does is set the target date for the Clock instance on the Stage. I’m using setTime() and Date.UTC() to convert the date to Universal Timecode. This way the date will be correct when it gets converted back to local time on the user’s computer. Also, remember that the months are zero-based. So, the month 4 is actually May, not April.

In your Flash file set the Document class to ‘Main’.

Set the Document Class

If you need a refresher on using the Document Class check out this Quick Tip.


Step 22: Test

Test your movie now and everything should work. Try changing the target date in the Main class and see how the countdown changes.

One potential downside to how we’ve set this up is that the target date is hard-coded in our SWF. That’s fine, but it would be cool if we could dynamically load the date so that we could reuse the countdown for different things.

Let’s see what we can do about that…


Step 23: Create the XML File

Create a new XML file in the same folder as your Flash file called ‘targetDate.xml’ (an XML file is just a plain text file). Add this to the XML file:

<targetDate>
	<year>2011</year>
	<month>3</month>
	<day>25</day>
	<hour>20</hour>
	<minute>21</minute>
</targetDate>

Using this format for our target date is pretty bloated (there is more markup than there is actual data), but it will keep things very clear for the purposes of this tutorial.


Step 24: Load the XML

Now let’s make some changes to our Main document class. Replace everything in that file with this code:

package {

	import flash.display.MovieClip;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.events.Event;

	public class Main extends MovieClip {

		// CONSTRUCTOR
		public function Main() {
			// load the XML
			var xmlLoader:URLLoader = new URLLoader();
			xmlLoader.addEventListener(Event.COMPLETE, onDataLoaded);
			xmlLoader.load( new URLRequest("targetDate.xml") );

		}

	}

}

You’ll notice we’ve imported some additional classes to help us load the XML file. In the constructor function we’re creating a new URLLoader instance to load the file for us. We attach an event listener that will call a function named ‘onDataLoaded’ when the file is finished loading.


Step 25: Add the onDataLoaded() Function

Add this function to the Main class:

private function onDataLoaded(e:Event):void {
	var xml:XML = new XML(e.target.data);

	var targetDate:Date = new Date();
	targetDate.setTime(Date.UTC(int(xml.year), int(xml.month), int(xml.day), int(xml.hour), int(xml.minute) ));

	clock.set(targetDate);
}

This function creates a new XML object from the file we loaded. We then create a new Date object from the values in the XML. We’re again using setTime() and Date.UTC() to convert the date to Universal Timecode. The final line is the same as before, it just sends the target date to our Clock instance.


Step 26: Wrap Up

That’s pretty much it for this one. There are a couple of enhancements you might like to make though:

  1. Depending on what you’re using the countdown for, you might want to do something special for the user when the countdown hits zero. You’d add this to the Clock class in the part of the update function that checks if the timer is at zero.
  2. As I mentioned, the format of our XML is pretty wasteful as it is. You might rather just pass in the date as a string via FlashVars, use a different data format (like JSON), or just reformat the XML to be a bit more compact.

Good luck! As always, post a comment and let me know what you think.

Add Comment

Discussion 77 Comments

Comment Page 2 of 2 1 2
  1. madebyross says:

    Great Tutorial, thank you for sharing.
    The only thing wich really annoys me is the ‘tic tic tic ‘there is no way i would put a sound like that on a page (or any sound/music). Just my 2 cents.
    Thank you again

  2. Vtania says:

    FIRST!!!
    Awesome tut….i’ve always wonderd the logic behind this. I thot i was gonna tween my way to a disease on this one….Thanx alot

  3. Danillo says:

    Very nice!! =)

  4. Jose Campos says:

    I like it jejeje, i built one just like this one some time ago which is a little bit simpler but in functionality it does the same you can check it out here: http://josecamposcr.blogspot.com/ but this is a really nice one too!

  5. alexxcz says:

    Very good tutorial. I absolutely love this effect! :) Good job!

  6. david says:

    demo is broken

    • eu4ria says:

      Online demo works, but downloaded example does not. Compiles and gives no errors but all counters are just stuck at 0.

  7. ArKeL says:

    Demo work, read “Step 11: Import the TweenLite Library”

  8. Kylio says:

    And thousands of flashden contributors just cried out in agony….

  9. row says:

    It’s easy to leave the sound out. Just skip step 20.

  10. Dimitree says:

    Nice tut. Though I think is not Intermediate but kind of advanced…(at least for me :))
    I get an error
    TypeError: Error #1006: set is not a function.
    at Main()

    Can you help with that?

    • Cadin says:
      Author

      It means it can’t find the set() function in your Clock class.

      Make sure you have an instance of the clock movieclip on your stage, that it has the instance name ‘clock’ and that it’s linked to the Clock class (in the linkage settings).

      • Dimitree says:

        Thanks for this… I guess it was the linkage thing – Clock class linked to the MovieClip.
        I d like to see more tutorials from you, as they are very well documented!

  11. Jarod says:

    What modifications would you have to make to make this a count “up” rather than a count down?

    • Cadin says:
      Author

      You just want it to count up continuously from 0?

      In that case you could modify the update() function.
      So when you set the ‘diff’ variable, instead of comparing the current time to the target time, you would just increment it by 1000 (1000 milliseconds = 1 second).

      That should get it working (I haven’t tested). After that you might want to go through and strip out all the targetDate and XML stuff since you won’t be needing it.

  12. LordOte says:

    Hi guys, i really like this countdown but it is absolutely complicated for me and what I want to use it for, I am a huge fan of flash and I was thinking put this movie into my hattrick’s team website but I actuality couldn’t make it works in my computer , I do not know how to use .as files or how upload to my space in ht-arena server.
    Could someone help me please?

    • LordOte says:

      Please anyone help me please, I’ve been looking this countdown for long time, so when I finally found it the thing does not work at all, when I make a publish preview it shows me a compiler error windows with the following information:
      Locatios: Clock.as, Line 2
      Description: 1046: Type was not found or was not a compile-time constant: TextField.

      Please Cadin help me! I want to use it in my hattrick team website (it is not for commercial use)

      • Cadin says:
        Author

        It sounds like you might be using Flash CS3. Is that right?

        If so you can probably get rid of the error by importing the TextField class.
        Add this line to the Clock.as:

        import flash.text.TextField;

        just below the other import statements.
        You might have to do that in a couple other places if you get more errors. CS3 doesn’t automatically import the classes you use in your linked MovieClips like CS4 does.

        Once you get it to publish you’ll need to upload the .swf, .xml and .html files.

  13. @Cadin

    Have you been inspired by my tutorial created for Webdesigner mag perhaps…?
    :)

  14. Good stuff. I was just wondering since the flipping principle with the “halves” is almost identical..required a lot of thinking(!) :)

    Good job though, well done mate.

    :)

  15. Ayaz Noor says:

    just a thought. is it possible to eliminate the animation from it and maintain the same classy looks (i.e. the background and all). if so, which step shall i skip. im not a pro at flash thats why wondering if the airport is ignorable. i just followed the whole tut at another site and in the end came errors. i just hate that.

    • Cadin says:
      Author

      If you don’t want to do any of the animation the project will be much simpler, though I don’t know if you can just skip a step here and have it work.

      You can probably just redesign the Digit movie clip to just have one text field for the number, forget about the 2 halves and the layering and all that. Then in the flipTo method remove all the tweens and just set the text of your textfield to the number.

      That should get it working with the least amount of modifications.

  16. mx says:

    Hi, thanks for the tutorial, i love how you created an array of strings to hold the number for each value, it’s a real eye opener for a newbie like me.

    i can sort of understand the concept behind everything, but i’m not too sure how to extend beyond it. right now i would like to add a mute button on the stage to toggle the ticking sound on and off. i tried a few things and i think i roughly got the idea, but essentially, i don’t think i know the right way to code it.

    could you please me a heads up on how to make this happen?

    thanks again!

    • Cadin says:
      Author

      Inside the event handler for the mute button you can call a function in Clock called toggleSound().

      You’ll have to add that function to the Clock class.
      Make it a public function so it can be accessed from outside the class.
      Inside the function you can toggle a boolean flag (‘_soundIsOn’) to indicate if the sound is on or not.

      In your update function, you’ll need to check the state of that variable and either play the tickSound or not.

      So something like this:

      // inside Main.as
      muteButton.addEventListener(MouseEvent.CLICK, onMuteClick);

      protected function onMuteClick(e:MouseEvent):void {
      clock.toggleMute();
      // probably do something here to the change the look of the mute button
      }

      // inside Clock.as
      private var _soundIsOn:Boolean = true;

      public function toggleMute():void {
      _soundIsOn = !_soundIsOn;
      }

      // inside update() function

      if(_soundIsOn){
      _tickSound.play();
      }

  17. Straight forward, easy to use and very effective… thank you!

  18. Javi says:

    Hola compañeros he compilado todo la demo con las libreias en su sitio “com” pero no consigo que establezca un contador. Me podeis decir que estoy haciendo mal, siempre me pone el contador en 0

    • Cadin says:
      Author

      What kind of error are you getting?
      Make sure the movie clips are linked to the proper classes in the library (Clock and Digit).

  19. j000 says:

    One of the best tutorials that I’ve read so far. Thanks a lot for sharing this valuable tutorial. Actually I needed this flipping effect to create something I’m working on.

  20. Javi says:

    Cadin.- In realy, It not show error, just that It no working animed, always show on 0, I think that the demo has no source or not completed.
    Can help me¡ Thanks

    • Cadin says:
      Author

      It sounds like you’re trying to count down to a date in the past.
      Be sure to change the target date in the XML file from the demo to the date you want to count down to.
      It probably has an old date from near the time when the tutorial was written.

  21. Twider says:

    Very good tutorial and very clear. But i’m a beginner and i would like to tweak it to count from a number like 5632 to 0. Is it possible and how i can achieve it? Thanks!

    • Cadin says:
      Author

      In that case you can strip out all the Dates and the time conversions in the update() function.

      Instead you can just have a variable to hold your number. Set it to the number you want to count down from. Then inside update(), decrement the variable and use it (as a String) in the diffString loop at the bottom to set all the digits in the Clock.

      You probably also want to reformat the Clock graphics to remove the colons and time references.

  22. Mohammad Ali says:

    plz upload video plz i can’t understand plz please plz plz i want to make this plz

  23. Tobias says:

    Hi, this tutorial rocks! I have one question: sometimes (after a while) the digits get all messed up. I noticed the font was Helvetica, I have Helvetica at a Mac (sometimes mac and PC fonts differ) and I see differences with yours. I provide a screenshot: http://www.imageupload.org/image.php?id=F419_4C4AC3E6

    Has anyone else experienced this? I don’t get it because in the beginning everything is going great, and after a while it get’s messed up, how freaky is that?

    • Cadin says:
      Author

      I haven’t ever seen that happen.
      It looks like a layering issue with the Digit movieclip, not a font problem. You’re seeing the upside-down ’2′ that should be hidden behind the top of the ’1′.

      I’m not sure why that’s happening. Are you using my file, or did you create your own?

  24. Michael says:

    Can U help me?
    On my computer everything works… but when I upload all files to server clock stuck on 0.
    I don’t now what i’m doing wrong.

  25. Michael says:

    forget.. my fail..everything working correctly :)

    • Abdel says:

      I have also the counters on 0 when uploaded into my website? you could help perhaps?

    • Bill says:

      Michael, what was the problem with the clock not working on the server? I’m having the same exact problem and can’t figure it out. Your help would be appreciated….or anyone’s….

  26. Andrea says:

    Hi Cadin,
    Great tutorial!

    I´m trying to instead of using a date/time, to make the counter count up to a specified number in the xml file. Could you please help me with that?

  27. Levi says:

    Hi Cadin,

    Awesome script, but I’ve got a minor problem. Everything works fine with the counter, except for a bug. This may be related to the ‘display’ function in flash – I don’t know.

    Try to open the swf in a browser tab
    Switch to another tab for at least 10 seconds, so the first digit of the seconds flipps.
    Now switch back to the swf’s tab and you’ll see that there is a layer that should not be visible. See this image: http://yfrog.com/n5countdownj

    Is there anything I can add that would check focus?

    Thanks,
    Levi

    • bftd says:

      I also have same bug.

    • tizio says:

      For anyone who is experiencing the upside-down number issue: it happens when the browser tab is inactive.

      That causes the swf to slow down to 2fps, which means a frame every 0.5s.

      But if you have putted tween animations lower than 0.5s, they will be skipped. This issue was scheduled and solved by the greensock team.

      The solution is to update the tweenlite libraries to the latest.

      Cheers!

  28. Great tutorial! Every step is well documented and explained.

    One problem though. My code is identical to yours, I’ve checked it against the sourcefiles provided, but I get an Error 1061: Call to a possibly undefined method set through a reference with static type Class.

  29. Jake Hardman says:

    Absolutely love this tutorial and concept. I think it would fit perfectly into our site and encourage more people to book tours etc. Willing to pay someone for A LOT of help!!!!

    Jake

  30. PIXELCHUNK says:

    I was looking for a method of achieving this effect, and the tutorial helped a lot. But in this function, why addchild ?

    private function reset():void
    {
    addChild(_nextDigit[BOTTOM]);
    addChild(_currentDigit[TOP]);
    // flip up the next bottom to be behind the current top
    _nextDigit[BOTTOM].scaleY = -1;
    _nextDigit[TOP].scaleY = 1;

    }

    The better way is this

    private function reset():void
    {
    setChildIndex(_nextDigit[BOTTOM], numchildren-1);
    setChildIndex(_currentDigit[TOP], numchildren-1);
    // flip up the next bottom to be behind the current top
    _nextDigit[BOTTOM].scaleY = -1;
    _nextDigit[TOP].scaleY = 1;

    }

    Cheers.

    • Staff

      Why do you say that method is better?

      • PIXELCHUNK says:

        I say it’s better because this way you get the same effect but the display list stays the same, numChild doesn’t increase. You won’t get two extra display objects for every second, I didn’t really tested it to see if there is any memory leakage but this way I’m sure that I don’t add/use anything that I don’t need (it’s my obsession), I just reuse everything and do object pooling.

      • Staff

        Ah, I see :) Actually, if you pass an object that already exists to addChild(), then all it does it move it to the top of the display list — it doesn’t create a duplicate, or increase numChildren. No need to worry about memory leakage or anything like that.

  31. simona says:

    purtroppo io non riesco a modificare la data anche modificando l’xml mi da sempre 16 dicembre 2010…:(

  32. Memory says:

    I get Type error 1013: The private attribute may be used only on class property difintion at private function update. (I use cs4)

    Can you help with that?

  33. Zack says:

    Hi

    I really like this tutorial but alas I have problem with step 5,

    Is like the Mask-layer supposed to be beneath the digit_bottom-layer or above and how do you select and delete the upper part of a movieClip.

    I wish someone could be kind and explain step 5 to me.

    Thanks

  34. Thomas Amos says:

    love it! Im sure this will come in handy. I was testing this out but managed to do it second time round. Im going to now create my own design and use it for when my clients have a website under construction.

    Thanks guys
    Amos Web Designs

  35. harleymagsino says:

    Hi Cadin,

    Great work.

    I just would like to know how can I put animations like loading a new movie when the counter reaches 0. I’m a bit rusty nowadays with AS so please supply with the syntax.

    Thanks!

    Harley

  36. vin says:

    Hi

    Flash tells me that there are errors:

    digit.as

    import com.greensock.*
    import com.greensock.easing.*

    TweenLite.to(_currentDigit[TOP], .15, {scaleY: 0, ease: Linear.easeNone});
    // flip the next digit bottom down
    TweenLite.to(_nextDigit[BOTTOM], .3, {scaleY:1, onComplete: flipComplete, ease: Bounce.easeOut});

    main.as

    targetDate.setTime(Date.UTC(int(xml.year), int(xml.month), int(xml.day), int(xml.hour), int(xml.minute) ));

  37. won says:

    Thanks for this. Everything’s working perfectly except for that the there might be error in the hour function.
    It’s not registering correctly. Right now it’s 6 pm and when I enter 19, in hour field in XML it gives me 0.
    When I enter 24, swf shows that I have 1 hour left until target date. So it seems The hour off by 6 hours.
    Also, month is counting from the 0. So January would be 0 in XML. Can you clarify where these errors could be fixed in clock action file? Thank you!

  38. Adriano says:

    I need some help, please…
    I have to change the timezone to GMT-3…
    How can I do it?

    Thnx

    • Jonathan says:

      @Adriano .. any luck changing the timezone? i am EST and the script isn’t showing the target date correctly. i even have a php script that sets the server timezone to New_York and it’s not working properly.

  39. Karl Macklin says:

    Nice design. I have to nitpick though (always striving for excellence) — the number switches on the top half before it’s flipped over!
    Not sure it was mentioned before, but that’s what I’m seeing if I screenshot it mid-flip.

  40. Abercharr says:

    Hi for starters lets say THNKS for this tut!

    I am a very new flash user and i just want to learn how i can make the flash take from FlashVars the expiration date.

    Thnks again…

  41. Ben says:

    Can anyone help me set up the days to accommodate 4 digits ? I want to have the counter counting down for a 5 year period? It’s for a screen saver. So there for, I need it to display 1825 days? Please inbox me the solution.

    Thanks very much, and great tutorial!

  42. Ware says:

    So yeah, i feel like a complete idiot here.
    But I really wanna make something like this for a site that I’m working on..
    And they want a countdown to their site “release”… So this would be downright awesome.

    Now, I don’t know much about Flash, other than I had it in school years ago…

    And there’s just one thing that boggles me. Allready imn step 2.. So this should be good I mean.. heh…

    Anyhow, my problem is that I know how I can take an element and and go modify – convert to symbol (F8), but where I loose you is how I can actually create a new movieclip?
    Cause the document here is 500×300, yet in step 3, you seem to have a much smaller work area. slightly confused.. Sorry for the trouble, and I’m sure there’s a really REALLY easy explanation to this though.. :S

  43. Roman says:

    Hi, Guys!
    I have a problem. Will you please have a look at the screenshot (http://imageshack.us/photo/my-images/560/unled1sed.jpg/). When counting down the picture sticks.
    Does anyone know what’s wrong?
    Thanks in advance!

  44. Ben says:

    Very well done! It was awesome! and really easy for me todo and learn from

  45. marsen says:

    is there any workaround to fix that messing bug that commented several times by several user ?

  46. Zdepa says:

    Great tutorial, thanks.
    Does enyone tried to develop it under as 2.0 ?. I need it in flash 8 and I stucked on these code:

    this["digit"+i].number
    and
    this["digit"+i].flipTo(diffString.substr(i, 1));

    There is no errors but if I add it to trace I can see it is undefined.
    From some reason it doesn’t work in as 2.0. I’m not advanced enough in flash to solved it by myself.
    Any help would be appreciated

  47. Justin says:

    Hi.
    I noticed in the last step “Wrap Up” you mention that you could have it do something special when the countdown timer hits zero, and that it could be placed in the Clock class, as part of the update function. I would like to have a redirect to a URL when the timer reaches zero, and I was thinking that I would just use getURL(), but I cannot seem to make this work for me. Do you have any suggestions as to how to make this work, or where exactly in the code I should place this (if this is even the correct way I should be coding it)?
    Thanks so much in advance.

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.