前几天在PC版本写的一个在线时长,犯了一个低级错误,在没有移除的情况下,重新调用了一次,导致时间不按正确的显示。
原因是:在定时器启动后,使用currentCount属性查询当前累计触发次数,使用“stop()”方法可以停止一个定时器。需要指出的是:“stop()”方法不过是暂停了定时器,并没有清除定时器。当一个定时器被“stop()”方法停止后,Timer对象的currentCount并没有被清除。当再次使用“start()”方法启动Timer对象时,定时器将继续执行,直到触发次数达到repeatCount属性规定的数值。用户不能在代码中为CurrentCount赋值,要改变 currentCount属性,只能使用“reset()”方法。“reset()”方法可以清零定时器的currentCount属性。
解决方法:不要重新调用初始时间函数了,重新写个函数, 函数里一定要reset()一下。
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="80" height="65"
xmlns:com="game.view.component.*" xmlns:help="game.help.*"
verticalScrollPolicy="off" horizontalScrollPolicy="off"
useHandCursor="true" buttonMode="true" creationComplete="init()" >
<mx:Script>
<![CDATA[
import game.events.RPCType;
import game.events.WarEvent;
import game.events.WarEventDispatcher;
import game.help.CoolDownTime;
import game.help.TimeUtil;
import game.manager.SocketManager;
import game.manager.UIManager;
import game.model.MainModelLocator;
import game.view.component.alert.AlertWindow;
[Bindable]
private var _model:MainModelLocator = MainModelLocator.getInstance();
[Bindable]
private var dispatch:WarEventDispatcher = WarEventDispatcher.getInstance();
private var timer:Timer = null;
private var t:int;
private function init():void
{
dispatch.addEventListener(WarEvent.EVENT_SYNC_OT_OVER,syncOc);
t = 0;
t = _model.OL_T;
onTimeHandler();
}
private function onTimeHandler():void
{
timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER,timerHandler);
timer.start();
}
private function syncOc(event:WarEvent):void
{
timer.reset();
t = 0;
t = _model.OL_T;
timer.start();
}
private function timerHandler(event:TimerEvent):void
{
txt.text = '';
if(t < _model.OL_M )
{
t++;
txt.text = transadvanceTime(t);
cav.styleName = 'online2';
}else
{
//与服务器时间同步
if(_model.sync)
{
SocketManager.getInstance().sendFeed(RPCType.SYNC_OT,{});
}else
{
timer.stop();
txt.text = transadvanceTime(t);
cav.styleName = 'online1';
}
}
}
private function transadvanceTime(timeNum:Number):String
{
var total_seconds:uint = Math.floor(timeNum);
var total_minutes:uint = Math.floor(total_seconds/60);
var total_hours:uint = Math.floor(total_minutes/60);
var total_days:uint = Math.floor(total_hours/24);
var days:uint = total_days;
var hours:uint = total_hours%24;
var minutes:uint = total_minutes%60;
var seconds:uint = total_seconds%60;
return (days==0?"":days.toString()+"天")+(hours<10?"0"+hours:hours.toString())+":"+(minutes<10?"0"+minutes:minutes.toString())+":"+(seconds<10?"0"+seconds:seconds.toString());
}
]]>
</mx:Script>
<mx:Canvas id="cav" styleName="{_model.OL_D?'online1':'online2'}" x="10" width="35" height="35"/>
<help:TextL id="txt" x="5" y="34" width="80" height="20"/>
</mx:Canvas>