1

这是简单的代码,但我无法解决.. 我点击 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;
    }
4

3 回答 3

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");
}
于 2013-02-11T02:07:20.900 回答
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();
}
于 2013-02-11T02:15:43.757 回答
-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();
    }
于 2013-02-11T02:10:09.847 回答