I am trying to dispatch event every second from Mytimer class and catch the event from Main class. I've declared variable "sus" as integer = 10. I have nothing so far, no output, nothing. Some help please!
This is Mytimer.as
private function onUpdateTime(event:Event):void
{
nCount--;
dispatchEvent(new Event("tickTack", true));
//Stop timer when it reaches 0
if (nCount == 0)
{
_timer.reset();
_timer.stop();
_timer.removeEventListener(TimerEvent.TIMER, onUpdateTime);
//Do something
}
}
And in Main.as I have:
public function Main()
{
// constructor code
_timer = new MyTimer ;
stage.addEventListener("tickTack", ontickTack);
}
function ontickTack(e:Event)
{
sus--;
trace(sus);
}
In your Main.as
, you have added the listener to the stage, not your timer. This line:
stage.addEventListener("tickTack", ontickTack);
should be like this:
_timer.addEventListener("tickTack", ontickTack);
But ActionScript already has a Timer
class that looks like it has all the functionality you need. No need to reinvent the wheel. Take a look at the documentation for the Timer class.
In your main you could just say:
var count:int = 10; // the number of times the timer will repeat.
_timer = new Timer(1000, count); // Creates timer of one second, with repeat.
_timer.addEventListener(TimerEvent.TIMER, handleTimerTimer);
_timer.addEventListener(TimerEvent.TIMER_COMPLETE, handleTimerTimerComplete);
Then just add your handler methods. You don't need to use both. Often the TIMER event is enough. Something like this:
private function handleTimerTimerComplete(e:TimerEvent):void
{
// Fires each time the timer reaches the interval.
}
private function handleTimerTimer(e:TimerEvent):void
{
// Fired when all repeat have finished.
}