-->

AS3 - Countdown timer color change

2019-09-06 15:30发布

问题:

With the help of an online tutorial, I created a simple 60 second countdown timer. I'd really like the text color to change to red once the timer hits 10 seconds. Any clue how I can add to this AS to make that happen?

Bonus question: when the timer hits zero, I'd love for the entire text field to fade out so that the zero isn't visible anymore. Any thoughts on that?

Here's my code, and thank you!!!

var nCount:Number = 60;
var myTimer:Timer = new Timer(1000, nCount);

timer_txt.text = nCount.toString();
myTimer.start();

myTimer.addEventListener(TimerEvent.TIMER, countdown);

function countdown(e:TimerEvent):void
{
    nCount--;
    timer_txt.text = nCount.toString();
}

回答1:

To change the color, add an if statement to your TimerEvent.TIMER handler.

To fade out at the end, add a listener for TimerEvent.COMPLETE.

import flash.events.TimerEvent;
import fl.transitions.Tween;
import fl.transitions.easing.None;

var nCount:Number = 60;
var myTimer:Timer = new Timer(1000, nCount);

timer_txt.text = nCount.toString();
myTimer.start();

myTimer.addEventListener(TimerEvent.TIMER, countdown);
// add a complete listener to fade out the TextField
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, fadeOut);

function countdown(e:TimerEvent):void
{
    nCount--;
    if(nCount == 10) 
    {
        // if the count is at 10, switch the text color to red
        timer_txt.textColor = 0xFF0000;
    }
    timer_txt.text = nCount.toString();
}

function fadeOut(e:TimerEvent):void 
{
    // I prefer GreenSock for tweening, but this is how you'd do it with the buil-in Flash Tween
    var t:Tween = new Tween(timer_txt, "alpha", None.easeNone, 1, 0, .5, true);
}