Timerの実行間隔テスト

by potix2
TimerEventの実行間隔のテスト
* 
* 結論:タイマーイベントはハンドラーの処理から指定間隔経過後に
* 呼び出される。
* ハンドラーの処理時間分だけずれることに注意が必要!
♥0 | Line 42 | Modified 2010-01-08 11:46:46 | MIT License
play

ActionScript3 source code

/**
 * Copyright potix2 ( http://wonderfl.net/user/potix2 )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/wrSC
 */

/**
 * TimerEventの実行間隔のテスト
 * 
 * 結論:タイマーイベントはハンドラーの処理から指定間隔経過後に
 * 呼び出される。
 * ハンドラーの処理時間分だけずれることに注意が必要!
 */
package {
	import flash.display.Sprite;
	import flash.events.TimerEvent;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.utils.Timer;
	import flash.utils.getTimer;

	public class TimerTest extends Sprite
	{
		private static const TIMER_INTERVAL:int = 1000;
		private var timer:Timer;
		private var _console:TextField;
		private var lastStartTime:int = 0;
		private var lastEndTime:int = 0;
		public function TimerTest()
		{
			_console = new TextField();
			_console.autoSize = TextFieldAutoSize.LEFT;
			addChild(_console);
			
			timer = new Timer(TIMER_INTERVAL, 0);
			timer.addEventListener(TimerEvent.TIMER, handlerTimer);
			timer.start();
		}
		
		private function handlerTimer(event:TimerEvent):void {
			var startTime:int = getTimer();
			log('handlerの開始: ' + startTime);
			log('  前回の開始時間との差: ' + (startTime - lastStartTime));
			log('  前回の終了時間との差: ' + (startTime - lastEndTime));
			var counter:int = 0;
			var interval:int = TIMER_INTERVAL * 0.8;
			while((getTimer() - startTime) < interval) {
				//時間のかかる処理をする
				counter++;
			}
			lastStartTime = startTime;
			lastEndTime = getTimer();
			log('handlerの終了時間: ' + lastEndTime);
		}
		
		private function log(message:String):void {
			_console.text = message + '\n' + _console.text;
		}
	}
}

Forked