【问题标题】:How to have Timer Count Down AS3如何让定时器倒计时 AS3
【发布时间】:2019-11-28 22:12:01
【问题描述】:

我有一个计时器,我试图让它倒计时而不是倒计时。几年前我使用过这段代码,似乎无法弄清楚如何让它从 5 分钟开始倒计时。

我只是尝试弄乱变量。

这是我的变量等:

tCountTimer = new Timer(100);
        tCountTimer.addEventListener(TimerEvent.TIMER, timerTickHandler);
        timerCount = 0;

        tCountTimer.start();

这是我要计算的函数:

private function timerTickHandler(e:Event):void 
    {
         timerCount += 100;
         toTimeCode(timerCount);
    }

    private function toTimeCode(milliseconds:int):void 
    {
        this.milliseconds = milliseconds;


        //create a date object using the elapsed milliseconds
        time = new Date(milliseconds);

        //define minutes/seconds/mseconds
        minutes = String(time.minutes + 5);
        seconds = String(time.seconds);
        miliseconds = String(Math.round(time.milliseconds) / 100);


        //add zero if neccecary, for example: 2:3.5 becomes 02:03.5
        minutes = (minutes.length != 2) ? '0'+ minutes : minutes;
        seconds = (seconds.length != 2) ? '0' + seconds : seconds;


        //display elapsed time on in a textfield on stage
        playScreen.timeLimitTextField.text = minutes + ":" + seconds;


    }

它算得上完美,但无法让它从 5 分钟开始计时。非常感谢所有帮助。

【问题讨论】:

    标签: actionscript-3 flash


    【解决方案1】:

    没有对此进行测试,但我希望这个想法绝对清楚。

    // Remember the time (in milliseconds) in 5 minutes from now.
    var endTime:int = getTimer() + 5 * 60 * 1000;
    
    // Call update function each frame.
    addEventListener(Event.ENTER_FRAME, onFrame);
    
    function onFrame(e:Event):void
    {
        // How many milliseconds left to target time.
        var aTime:int = endTime - getTimer();
    
        // Fix if we are past target time.
        if (aTime < 0) aTime = 0;
    
        // Convert remaining time from milliseconds to seconds.
        aTime /= 1000;
    
        // Convert the result into text:
        // aTime % 60 = seconds (with minutes stripped off)
        // aTime / 60 = full minutes left
        var aText:String = ze(aTime / 60) + ":" + ze(aTime % 60);
    
        // Do whatever you want with it.
        trace(aText);
    }
    
    // Function to convert int to String
    // and add a leading zero if necessary.
    function ze(value:int):String
    {
        return ((value < 10)? "0": "") + value.toString();
    }
    

    【讨论】:

    • 所以不是使用计时器,而是使用 ENTER_FRAME 事件?
    • @NathanFitchett 实际上这不是重要的部分。 TimerENTER_FRAME 只是定期调用方法的手段。您可以用 Timer 调用替换我代码中的这一部分,它不会改变任何事情。
    • 非常感谢您,这很完美。正是我想要的,而且更简单哈哈
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    相关资源
    最近更新 更多