Search code examples
actionscript-3mouseoverstopwatch

Timer gives error AS3


I've some trouble with the timer. My goal is to call it when MOUSE_OVER and to kill it when MOUSE_OUT.

Function to start timer:

   public function timerStart():void {
                var myTimer:Timer = new Timer(1000, 1); // 1 second
                myTimer.addEventListener(TimerEvent.TIMER, runOnce);
                myTimer.start();
            }

Function to stop timer:

    public function timerStop():void {
        myTimer.stop();
    }

Function to call timer:

public function rollOverHandler(e:MouseEvent = null):void 
        {

        timerStart();
}

Function to call stop timer:

    internal final function rollOutHandler(e:MouseEvent = null):void 
    {
    timerStop(); //this one created the error message
}

Whatever I try, I keep getting this error message:

1120: Access of undefined property myTimer.

I understand the fact that he can't stop a timer which he doesn't recognize. But I am getting the error even before any mouseaction. What am I seeing wrong?

Does someone know a solution?


Solution

  • The problem is scope: You are declaring myTimer as a local variable. The reference will be deleted after timerStart() is executed.

    Make it a member variable, and everything should work fine.

    Oh, and also: Do this in the rollOutHandler:

    if (myTimer != null) timerStop();
    

    to make sure it only gets called if a timer has been set.