在倒计时中添加或删除时间

时间:2012-03-24 07:05:47

标签: actionscript-3 flash timer

我有一个计时器脚本:

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

var secs:Number = 30;//second
var mins:Number = 2;//minute
var sec_t:String;
var min_t:String;

var my_timer:Timer = new Timer(1000);
my_timer.addEventListener(TimerEvent.TIMER, timerHandler);
my_timer.start();
showTimer.text = "02:30";

function timerHandler(event:TimerEvent):void
{
    if (secs == 0)
    {
        if (mins == 0)
        {
            my_timer.stop();
            trace("Countdown is finished.");
            showTimer.text =String(min_t+sec_t)+" Times Up";
            return;
        }
        else
        {
            --mins;
            secs = 59;
        }
    }
    else
    {
        --secs;
    }
    sec_t = (secs < 10) ? "0" + String(secs):String(secs);
    min_t = (mins < 10) ? "0" + String(mins) + ":":String(mins) + ":";
    trace(min_t+sec_t);
    showTimer.text =String(min_t+sec_t);
}

wrongBtn.addEventListener(MouseEvent.CLICK, wrongClick);
function wrongClick(event:MouseEvent):void
{
    secs = secs - 10;
}

correctBtn.addEventListener(MouseEvent.CLICK, correctClick);
function correctClick(event:MouseEvent):void
{
    secs = secs + 10;
}

有两个按钮wrongBtncorrectBtnwrongBtn会减少10秒的时间,correctBtn会增加10秒的时间。 但是当计时器秒数大约是2:05并且我按wrongBtn时,时间显示不正确,如下所示:“2:0-5”。同样,当时间大约是2:55并按correctBtn时,时间将显示为“2:65”......

如何使其正常工作,以便正确显示输出?

1 个答案:

答案 0 :(得分:5)

保持一个计时器计数而不是单独的分钟和秒。您可以安全地增加和减少它,并始终保持正确的时间。为了使其可读,只需格式化输出:

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


var timeRemaining:int = 150; // 150 seconds => 2:30 mins

showTime.text = formatTimeRemaining();

var timer : Timer = new Timer (1000);
timer.addEventListener (TimerEvent.TIMER, onTimer);
timer.start();


function onTimer ( ev:TimerEvent ) : void {
    timeRemaining--;
    if (timeRemaining < 0) {
        timeRemaining = 0;
        loseGame();
    }
    else 
        showTime.text = formatTimeRemaining ();
}

function formatTimeRemaining () : String {
    var mins : int = int (timeRemaining / 60);
    var minstr : String = mins < 10 ? "0"+mins : ""+mins;
    var secs : int = timeRemaining % 60;
    var secstr : String = secs < 10 ? "0"+secs : ""+secs;

    return minstr+":"+secstr;
}

function loseGame () : void {
    timer.stop();
    trace("Countdown is finished.");
    showTime.text = formatTimeRemaining() + (" Time's Up!");
}

wrongBtn.addEventListener(MouseEvent.CLICK, wrongClick);
function wrongClick(event:MouseEvent):void
{
    timeRemaining -= 10;
}

correctBtn.addEventListener(MouseEvent.CLICK, correctClick);
function correctClick(event:MouseEvent):void
{
    timeRemaining += 10;
}