PageRenderTime 4ms CodeModel.GetById 1ms app.highlight 1ms RepoModel.GetById 1ms app.codeStats 0ms

/src/as/gs/util/FrameDelay.as

https://github.com/zeratel/guttershark
ActionScript | 91 lines | 44 code | 9 blank | 38 comment | 5 complexity | d2e48459e749d4db582e9dcecf4fd1a2 MD5 | raw file
 1package gs.util
 2{
 3	
 4	import flash.events.Event;
 5	
 6	/**
 7	 * The FrameDelay class allows for a callback to be called after
 8	 * a certain amount of frames have passed.
 9	 * 
10	 * @example Using a FrameDelay:
11	 * <listing>	
12	 * var fd:FrameDelay=new FrameDelay(after10, 10);
13	 * function after10():void
14	 * {
15	 *     trace("10 frames have passed");
16	 * }
17	 * </listing>
18	 */
19	final public class FrameDelay
20	{
21		
22		/**
23		 * is done flag.
24		 */
25		private var isDone:Boolean;
26		
27		/**
28		 * The current frame.
29		 */
30		private var currentFrame:int;
31		
32		/**
33		 * The callback.
34		 */
35		private var callback:Function;
36		
37		/**
38		 * Parameters to send to the callback.
39		 */
40		private var params:Array;
41		
42		/**
43		 * Constructor for FrameDelay instances.
44		 * 
45		 * @param callback The callback to call.
46		 * @param frameCount The number of frames to wait.
47		 * @param params An array of parameters to send to your callback.
48		 */
49		public function FrameDelay(callback:Function,frameCount:int=0,params:Array=null)
50		{
51			currentFrame=frameCount;
52			this.callback=callback;
53			this.params=params;
54			isDone=(isNaN(frameCount) || (frameCount <= 1));
55			FramePulse.AddEnterFrameListener(handleEnterFrame);
56		}
57		
58		/**
59		 * Handle an enter frame event.
60		 */
61		private function handleEnterFrame(e:Event):void
62		{
63			if(isDone)
64			{
65				if(params==null)callback();
66				else callback.apply(null,params);
67				dispose();
68			}
69			else
70			{
71				currentFrame--;
72				isDone=(currentFrame<=1);
73			}
74		}
75		
76		/**
77		 * Dispose of this FrameDelay instance.
78		 */
79		public function dispose():void
80		{
81			if(isDone)
82			{
83				FramePulse.RemoveEnterFrameListener(handleEnterFrame);
84				params=null;
85				callback=null;
86				currentFrame=0;
87				isDone=false;
88			}
89		}
90	}
91}