User Guide

Example: Alarm Clock 367
The Timer instance defined in the AlarmClock class is named alarmTimer. The
initClock() method, which performs necessary setup operations for the AlarmClock
instance, does two things with the
alarmTimer variable. First, the variable is instantiated with
parameters instructing the Timer instance to wait 0 milliseconds and only trigger its timer
event one time. After instantiating
alarmTimer, the code calls that variables
addEventListener() method to indicate that it wants to listen to that variable’s timer event.
A Timer instance works by dispatching its
timer event after a specified amount of time has
passed. The AlarmClock class will need to know when the
timer event is dispatched in order
to set off its own alarm. By calling
addEventListener(), the AlarmClock code registers itself
as a listener with
alarmTimer. The two parameters indicate that the AlarmClock class wants
to listen for the
timer event (indicated by the constant TimerEvent.TIMER), and that when
the event happens, the AlarmClock classs
onAlarm() method should be called in response to
the event.
In order to actually set the alarm, the AlarmClock class’s
setAlarm() method is called, as
follows:
/**
* Sets the time at which the alarm should go off.
* @param hour The hour portion of the alarm time.
* @param minutes The minutes portion of the alarm time.
* @param message The message to display when the alarm goes off.
* @return The time at which the alarm will go off.
*/
public function setAlarm(hour:Number = 0, minutes:Number = 0,
message:String = "Alarm!"):Date
{
this.alarmMessage = message;
var now:Date = new Date();
// Create this time on today's date.
alarmTime = new Date(now.fullYear, now.month, now.date, hour, minutes);
// Determine if the specified time has already passed today.
if (alarmTime <= now)
{
alarmTime.setTime(alarmTime.time + MILLISECONDS_PER_DAY);
}
// Stop the alarm timer if it's currently set.
alarmTimer.reset();
// Calculate how many milliseconds should pass before the alarm should
// go off (the difference between the alarm time and now) and set that
// value as the delay for the alarm timer.
alarmTimer.delay = Math.max(1000, alarmTime.time - now.time);
alarmTimer.start();
return alarmTime;
}