views:

128

answers:

3

I'm tracking how fast does the text of a textArea change. If it changes faster than 500 ms then i don't want to do anything, but if it doesn't change in 500 ms, i want to call a method. I tried like this:

public function textchangeListener(e : Event):void
        {
            if(((new Date).getTime() - changeTime)>500)
            {
                prepareText();
            }

            changeTime = (new Date).getTime();
        }

This method is the event handler for text change. But the problem is, if it changes only under 500 ms and after that it doesn't change, then my method won't be called. I make this for a better performance, so the prepareText() is called only when the user stops typing for 500 ms.

+1  A: 

How about this...

Once you get the first text change event you can call a procedure like textTimeOut(). It will essentially work like this.

function textTimeOut():void
{
    start a timer for 500 ms
    set an event listener for it (your prepareText() function)
    if textTimeOut is called again before the timer gets to 0,
        reset the timer to 500 ms
}
Ryan M
A: 

I would use a setTimeout in the event handler and reset it everytime it changes:

var changeTimeout:Number = -1
function handler(e:Event):void {
    if(changeTimeout != -1)
        clearTimeout(changeTimeout)
    changeTimeout = setTimeout(function():void{
        changeTimeout = -1
        prepareText();
    }, 500)
}
sharvey
A: 

So I used a timer. Thanks for the advice. This is what the end result is:

    protected var timer:Timer = new Timer(300);

public function AdvancedTextArea()
        {
            super();
            this.addEventListener(Event.CHANGE,textchangeListener);
            timer.addEventListener(TimerEvent.TIMER,prepareText);
            timer.repeatCount = 1;

        }
public function textchangeListener(e : Event):void
        {
            if(timer.running)
            {
                timer.stop();
            }
            timer.start();

        }
Biroka