as3计时工具类

来源:互联网 发布:mcmc算法 编辑:程序博客网 时间:2024/04/28 05:37

写一个计时工具类 有不对的地方还行多多包涵。。。大笑


package com.util

{
import flash.events.Event;
import flash.events.TimerEvent;
import flash.utils.Dictionary;
import flash.utils.Timer;
import flash.utils.getTimer;



/**
* 计时工具
* @author azu
*/
public class TimerUtil
{
private static var instance:TimerUtil;

/**定时器*/
private var timer:Timer = new Timer(10);
/** 计时器列表 */
private var timerList:Dictionary = new Dictionary(true);



public function TimerUtil():void
{
timer.addEventListener(TimerEvent.TIMER, onEnterFrame);
timer.start();
}

public static function getInstance():TimerUtil
{
return instance ||= new TimerUtil();
}

/**
* 添加计时器
* @param callFun定时器回调函数.
* @param delay 定时器执行时间,以毫秒为单位,1秒等于1000毫秒.
* @param reCount定时器执行次数, 0为无限次数,默认为0.
* @return 计时器编号
*
*/
public function addTimer(callFun:Function, delay:int, reCount:int = 0):void
{
var item:DataTimer = timerList[callFun];
if(item)
{
item.delay = delay;
item.reCount = reCount;
item.initTime = getTimer();
}
else
{
var DataTimer:DataTimer = new DataTimer(delay, reCount, getTimer(), callFun);
timerList[callFun] = DataTimer;
}
}

/**
* 计算时间
* @param e
*
*/
private function onEnterFrame(e:Event):void
{
var nowTime:int = getTimer();
for each (var item:DataTimer in timerList)
{
var delay:int = nowTime - item.initTime;
if (delay >= item.delay) //时间到
{
item.initTime = nowTime;
var num:int = delay / item.delay;
//trace("需要执行次数", num);
while (num > 0)
{
num--;
item.callFun();
if (item.reCount != 0) //总执行次数
{
item.reCount--;
if (item.reCount <= 0) //计数次数达到
{
delete timerList[item.callFun];
item = null;
break;
}
}
}

}
}

}


/**
* 移除计时器
* @param callFun
*
*/
public function removeTimer(callFun:Function):void
{
var item:DataTimer = timerList[callFun];
if(item)
{
delete timerList[item.callFun];
item = null;
}
}



}

}




/**
 * 计时器列表中的对象格式 
 * @author azu
 * 
 */
class DataTimer
{
/** delay:时长 */
public var delay:int = 0;
/** reCount:计时次数 */
public var reCount:int = 0;
/** initTime:初始时间 */
public var initTime:int = 0;
/** callFun:触发的回调方法 */
public var callFun:Function;


public function DataTimer(_delay:int, _reCount:int, _initTime:int, _callFun:Function)
{
delay = _delay;
reCount = _reCount;
initTime = _initTime;
callFun = _callFun;
}

}






0 0
原创粉丝点击