较timer更为准确的倒计时方法
从同事处得来一较为准确的倒计时方法。
Timer的计时由于帧频原因或者CPU占用过高,会随着时间推移而越发不准确。
应对办法之一就是每隔一段时间(例如300ms)校正一次,进而达到接近准确的目的。
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 55 56 57
| private static var countdownTimer:Timer = new Timer(300); private static var timestamp:Number = 0; private static var countdowns:Array = []; private static var countdownSeconds : Dictionary = new Dictionary();
public static function addCountdown(method:Function, second:Number):void { var index:int = countdowns.indexOf(method); if (index >= 0) { return; } if (!countdownTimer.hasEventListener(TimerEvent.TIMER)) { countdownTimer.addEventListener(TimerEvent.TIMER, countDownHandler); } if (!countdownTimer.running) { timestamp = getTimer(); countdownTimer.start(); } countdowns.push(method); countdownSeconds[method] = second; }
public static function removeCountdown(method:Function):void { if (method == null) { return; } var index:int = countdowns.indexOf(method); if (index >= 0) { countdowns.splice(index, 1); countdownSeconds[method] = null; delete countdownSeconds[method]; } if (countdowns.length == 0) { countdownTimer.stop(); } }
private static function countDownHandler(e:TimerEvent):void { var remain:Number = (getTimer() - timestamp) * 0.001; timestamp = getTimer(); for (var i:int = 0; i < countdowns.length; i++) { var func:Function = countdowns[i]; var second:Number = countdownSeconds[func]; second -= remain; func(second); countdownSeconds[func] = second; } }
|
21 Aug 2015
page PV: ・
site PV: ・
site UV: