Reputation: 6485
I am working on an app, where the server time needs to be displayed on a Flex app. The idea is to make a BlazeDS remoting call getServerTime() once during the app intialization and then use a local Timer class to keep updating the display.( I don't want to bombard server with getServerTime() for each second).
My question is, once I have a AS3 Date object. How do I increment it by seconds?
//remoteServerDateTime value is already set by a remote blazeds call
[Bindable]
var serverTime:Date = remoteServerDateTime;
public function updateTime():void
{
//I am trying to add code here that increments serverTime by 1 sec.
serverTime = serverTime + 1 // this wont work
ticker = new Timer(1,1);
ticker.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
ticker.start();
}
public function onTimerComplete(event:TimerEvent):void{
updateTime();
}
//creationComplete = updateTime();
//MXML <mx:Label text={serverTime} "/>
Upvotes: 3
Views: 1581
Reputation: 9013
You need to use getTime()
, not getSeconds()
:
serverTime.setTime(serverTime.getTime() + 1000);
Having a timer fire once per second is a good approach to get notified when it's time to update the cached server time, but your code creates a new timer after every call and discards the old timer. The difference is that a single timer instance does not get delayed by the time its timerComplete listener takes, while your code does.
If it takes x seconds from the start of onTimerComplete
to the call of ticker.start()
, onTimerComplete
is called every x+1 seconds, not every 1 second. Therefore, serverTime
might get incremented by less that 60 seconds per minute.
The difference may be negligible (you should test it). If it is not, use a single timer instance with repeatCount 0, which is started when the server time arrives.
You may also want to compute the current server time by adding the precomputed time difference between the client and the server. This way you are independent of any irregularities in the timer, e.g. because it was delayed due to long computations.
// Initialized when the server responds:
// difference = server time minus local time, in milliseconds
var localToServerDifference:Number =
remoteServerDateTime.getTime() - new Date().getTime();
public function updateTime():void
{
// server time = local time plus difference
serverTime.setTime(new Date().getTime() + localToServerDifference);
}
Upvotes: 2