无法停止定时器AS3

时间:2013-02-11 02:00:58

标签: actionscript-3 flash

这是简单的代码,但我无法解决.. 我点击a.button,所以计时器运行,但如果我点击b.button,计时器仍在运行。如何阻止这个计时器?谢谢 (对不起,我的英文不好)

    a.addEventListener(MouseEvent.CLICK, starts);
    function starts(e:MouseEvent)
    {
            time(0);
    }
    b.addEventListener(MouseEvent.CLICK, stops);
    function stops(e:MouseEvent)
    {
            time(1);
    }
    function time(cc)
    {
        var timer:Timer = new Timer(1000,100);
        timer.addEventListener(TimerEvent.TIMER, tmer);
        timer.start();
        function tmer(e:TimerEvent):void
        {
            trace("start");
        }
        if(cc == 1)
        {
            trace("stop");
            timer.stop();
            timer.removeEventListener(TimerEvent.TIMER, tmer);
        }
        cc=0;
    }

3 个答案:

答案 0 :(得分:1)

尝试这个:

a.addEventListener(MouseEvent.CLICK, starts);
function starts(e:MouseEvent)
{
    time(0);
}
b.addEventListener(MouseEvent.CLICK, stops);
function stops(e:MouseEvent)
{
    time(1);
}

var timer:Timer;
function time(cc:int)
{
    if(cc == 0)
    {
        if(!timer)
            timer = new Timer(1000,100);        
        timer.addEventListener(TimerEvent.TIMER, tmer);
        timer.start();
    }   
    else if (cc == 1)
    {
        trace("stop");
        timer.stop();
        timer.removeEventListener(TimerEvent.TIMER, tmer);
    }
}

function tmer(e:TimerEvent):void
{
    trace("start");
}

答案 1 :(得分:1)

请改为尝试:

var timer:Timer = new Timer(1000,100);

// To verify if timer is running or stopping
timer.addEventListener(TimerEvent.TIMER, tickTock);
function tickTock(e:TimerEvent):void
{
    trace("tick tock");
}

a.addEventListener(MouseEvent.CLICK, starts);
function starts(e:MouseEvent)
{
        time(0);
}

b.addEventListener(MouseEvent.CLICK, stops);
function stops(e:MouseEvent)
{
        time(1);
}

function time(cc)
{
    if(cc == 0)
    {
        trace("start");
        timer.start();
    }
    else if(cc == 1)
    {
        trace("stop");
        timer.stop();
    }
}

或者简单地说:

var timer:Timer = new Timer(1000,100);

// To verify if timer is running or stopping
timer.addEventListener(TimerEvent.TIMER, tickTock);
function tickTock(e:TimerEvent):void
{
    trace("tick tock");
}

a.addEventListener(MouseEvent.CLICK, starts);
function starts(e:MouseEvent)
{
        trace("start");
        timer.start();
}

b.addEventListener(MouseEvent.CLICK, stops);
function stops(e:MouseEvent)
{
        trace("stop");
        timer.stop();
}

答案 2 :(得分:-1)

这是因为第二次创建新的Timer对象。

var timer:Timer = new Timer(1000,1000);
function tmer(event:TimerEvent):void{
     trace("The timer is working");
}
timer.addEventListener(TimerEvent.TIMER, tmer);
timer.stop();
 a.addEventListener(MouseEvent.CLICK, starts);
    function starts(e:MouseEvent)
    {
            timer.reset();
            timer.start();
    }
    b.addEventListener(MouseEvent.CLICK, stops);
    function stops(e:MouseEvent)
    {
            timer.stop();
    }