Evan Moscowa
Evan Moscowa

Reputation: 35

Use button to enable timer inside a function

I'm making something in actionscript 3, and when I press the first button btnSkaffPenger, it increases the number by 1 for each click. But my second button btnTrePrinter is supposed to increase the number by 1 every 2 seconds, automatically, but only works once, and doesnt reset. (I added so you can only press the button once, I don't think that interferes with the function resetting)

Thanks

The buttons code:

btnTrePrinter.addEventListener(MouseEvent.CLICK, trePrinter);
function trePrinter(evt:MouseEvent):void
{
    var timer:Timer = new Timer(2000);
    var harVentet:Function = function(event:TimerEvent):void{
        timer.removeEventListener(TimerEvent.TIMER, harVentet);
        timer = null;

        sumPenger++
        txtSumPenger.text = sumPenger.toString();
    }
    timer.addEventListener(TimerEvent.TIMER, harVentet);
    timer.start();

    btnTrePrinter.mouseEnabled = false;
    btnTrePrinter.alpha=0.4;
}

Full code:

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

var sumPenger:int = 0;

btnSkaffPenger.addEventListener(MouseEvent.CLICK, penger1);
function penger1(evt:MouseEvent):void
{
    sumPenger++
    txtSumPenger.text = sumPenger.toString();
}

btnTrePrinter.addEventListener(MouseEvent.CLICK, trePrinter);
function trePrinter(evt:MouseEvent):void
{
    var timer:Timer = new Timer(2000);
    var harVentet:Function = function(event:TimerEvent):void{
        timer.removeEventListener(TimerEvent.TIMER, harVentet);
        timer = null;

        sumPenger++
        txtSumPenger.text = sumPenger.toString();
    }
    timer.addEventListener(TimerEvent.TIMER, harVentet);
    timer.start();

    btnTrePrinter.mouseEnabled = false;
    btnTrePrinter.alpha=0.4;
}

Upvotes: 1

Views: 82

Answers (1)

Nbooo
Nbooo

Reputation: 865

As I was told, it's a bad practice to put the answer in comments, so I post it once again.

Just to clarify what happens in your code:

var timer:Timer = new Timer(2000);
// the timer created with 2 seconds delay and infinite repeats 

var harVentet:Function = function(event:TimerEvent):void {
    // 2 seconds passed after "timer.start()" call
    // it's the first invocation of this listener
    timer.removeEventListener(TimerEvent.TIMER, harVentet);
    timer = null;
    // the listener is removed and timer is destroyed
    // since the listener removed from timer, no more invocations will happen
    sumPenger++
    txtSumPenger.text = sumPenger.toString();
}
timer.addEventListener(TimerEvent.TIMER, harVentet);
// the listener is added to timer
timer.start();
// the timer starts

Remove this code:

timer.removeEventListener(TimerEvent.TIMER, harVentet);
timer = null;

and the timer will work as you expect.

Upvotes: 1

Related Questions