Not yet rated

Problem

Changing properties of display object isn't always successful in the timer event handler when the handler is a function in function

Solution

When trying to acess properties of display object within timer event handler, be careful not to use function in function as the handler

Detailed explanation

To implement a blinking effect of some button, one can use a timer with limited repeat count to flip the visible property in the timer event  and set back visible when timer complete, as follows:

import flash.utils.Timer;
import flash.events.TimerEvent; 

function doBLinkingButton():void 
{
    function handleTimer(e:TimerEvent):void 
    { 
        myButton.visible = !myButton.visible; 
    }

    function handleCompleteTimer(e:TimerEvent):void 
    { 
        myButton.visible = true;
    }

    // repeat timer 6 times with 0.5-second cycle 
    Timer tmr:Timer = new Timer(500, 6); 
    tmr.addEventListener(TimerEvent.TIMER, handleTimer); 
    tmr.addEventListener(TimerEvent.TIMER_COMPLETE,
handleCompleteTimer); 
}

Looking good, right?

If you run this code, you'll find for even-number times the handler executes, the flipping of visible properties won't succeed! The reason is because we are using a function in function as an event handler.

If you move handleTimer function outside doBLinkingButtion function to make it a class-level method, then the flipping will succeed each time handleTimer is called.

 


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes