1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package Timer
{
	import flash.display.Shape;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	
	public class AccurateTimer extends EventDispatcher
	{
		// EnterFrame 註冊
		private var shape:Shape;
		
		//上一次EnterFrame 的時間點
		private var lastTime:int;
		
		//距離上一次叫之後經過了多久
		private var timeError:uint;
		
		//已經叫幾次了
		public var currentCount:uint;
		
		//多久叫一次
		public  var delay :uint = 1000;
		
		public function AccurateTimer(delay:uint)
		{
			shape = new Shape();
			this.delay = delay;
		}
		
		public function start():void{
			timeError = 0;
			currentCount = 0;
			lastTime = new Date().valueOf();
			shape.addEventListener(Event.ENTER_FRAME,onEnterFrameHandler);
		}
		public function stop():void{
			shape.removeEventListener(Event.ENTER_FRAME,onEnterFrameHandler);
		}
		
		public function onEnterFrameHandler(e:Event):void{
			var nowTime :int = new Date().valueOf();
			timeError += nowTime - lastTime;
			lastTime = nowTime;
			
			while (timeError >= delay)
			{
				timeError -= delay;
				this.dispatchEvent(new TimerEvent(TimerEvent.TIMER));
				currentCount++;
			}
		}
	}
}