Search code examples
actionscript-3flashtimeraddeventlistener

addEventListener stops code in timer


I have two blue squares that appear and disappear with the click of the * key. One click has a timer on it. The code works the first time around, but the second time it stops working. In debugger it stopped on the line

timer.addEventListener(TimerEvent.TIMER, timerB);

Not really sure why it works the first time, but not the second time.

var onOff:Boolean = false;


// Off Timer
var timer:Timer = new Timer(300);

function timerA(event:KeyboardEvent):void {
    blue1.visible = false;
    timer.addEventListener(TimerEvent.TIMER, timerB);
    timer.start();
}

function timerB(event:TimerEvent):void {
    timer.removeEventListener(TimerEvent.TIMER, timerB);
    timer.stop();
    blue2.visible = false;
}

stage.addEventListener(KeyboardEvent.KEY_UP,turnoff);

function turnoff(event:KeyboardEvent):void { 
    if (event.keyCode == 106) {
        if (onOff == false) {
            timerA(null);
            onOff = true;
        } else if (onOff == true) {
            blue1.visible = true;
            blue2.visible = true;
            onOff = false;
        }
    }
}

Solution

  • Who did timer = null; in TimerB()? There goes your timer. You should instead call timer.stop().