Flex之无延时定时器

在写定时器的时候,我们希望第一次开启定时器不用延时,直接加载。

而不用再等待该定时器设定的时间就直接运行。也是就说无延时定时器

下面我举个简单的例子加以说明。

MyTimer.as:

package com.utils.allas
{
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	public class MyTimer extends Timer {
		private var startDelay:Boolean;
		public function MyTimer(delay:Number, repeatCount:int = 0, startDelay:Boolean = true) {
			this.startDelay = startDelay;
			super(delay, repeatCount);
		}
		public override function start():void {
			if (!startDelay) dispatchEvent(new TimerEvent(TimerEvent.TIMER));
			super.start();
		}
	}
}

TestTimer.as:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
			   initialize="application1_initializeHandler(event)"
			   
			   >
	<fx:Declarations>
		<!-- 将非可视元素(例如服务、值对象)放在此处 -->
	</fx:Declarations>
	<fx:Script>
		<![CDATA[
			import com.utils.allas.MyTimer;
			
			import mx.events.FlexEvent;
			
			import  flash.events.TimerEvent;
			import mx.controls.Alert;
			
			protected function application1_initializeHandler(event:FlexEvent):void
			{
				// TODO Auto-generated method stub
				var timer:MyTimer = new MyTimer(5000, 5, false);
				timer.addEventListener(TimerEvent.TIMER, timerHandler);
				timer.start();
			}
			
			public function timerHandler(event:TimerEvent):void{
				Alert.show("你好");
			}
			
		]]>
	</fx:Script>
</s:Application>

注意:

  不延迟第一次调度timer事件不会计入到计时器的总运行次数repeatCount的。即调度完第一次timer事件后,currentCount仍为0。

你可能感兴趣的:(Flex之无延时定时器)