Cyril_Hyori
Cyril_Hyori

Reputation: 19

How to reduce the timer's time while timer is running (ActionScript 3.0)

In my case, the timer I make doesn't reduce its time whenever a function is called. What code will I change or add in order to reduce the time in my timer?

Timer code:

var count:Number = 1200;
var lessTime:Number = 180;
var totalSecondsLeft:Number = 0;
var timer:Timer = new Timer(1000, count);
timer.addEventListener(TimerEvent.TIMER, countdown);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, timesup);

function countdown(event:TimerEvent) {
    totalSecondsLeft = count - timer.currentCount;
    this.mainmc.time_txt.text = timeFormat(totalSecondsLeft);
}

function timeFormat(seconds:int):String {
var minutes:int;
var sMinutes:String;
var sSeconds:String;
if(seconds > 59) {
    minutes = Math.floor(seconds / 60);
    sMinutes = String(minutes);
    sSeconds = String(seconds % 60);
    } else {
    sMinutes = "";
    sSeconds = String(seconds);
}
if(sSeconds.length == 1) {
    sSeconds = "0" + sSeconds;
}
return sMinutes + ":" + sSeconds;
}

function timesup(e:TimerEvent):void {
    gotoAndPlay(14);
}

At this point the timer.start(); is placed on a frame so that the timer starts as it enters the frame.

Upvotes: 0

Views: 4017

Answers (1)

redhotvengeance
redhotvengeance

Reputation: 27866

The delay property on Timer is what you are looking for. In your handler, change the timer's delay:

function countdown(event:TimerEvent)
{
    totalSecondsLeft = count - timer.currentCount;
    this.mainmc.time_txt.text = timeFormat(totalSecondsLeft);

    //change the timer delay
    timer.delay -= lessTime;
}

I assumed by your code sample that you wanted to subtract lessTime from the timer delay on each timer interval. If you want to change the delay to something else, then just adjust the code accordingly.

UPDATE
The above code is for decreasing the interval (delay) between each timer fire. If what you'd like to do instead is decrease the the amount of intervals (repeatCount) it takes for the timer to reach TIMER_COMPLETE, then you want to change the repeatCount property on Timer:

//set the timer fire interval to 1 second (1000 milliseconds)
//and the total timer time to 1200 seconds (1200 repeatCount)
var timer:Timer = new Timer(1000, 1200);

//reduce the overall timer length by 3 minutes
timer.repeatCount -= 300;

ANOTHER UPDATE
Keep in mind that when you alter the repeatCount, it doesn't affect the currentCount. Since you are using a separate count variable and timer.currentCount to calculate the displayed time remaining, it doesn't look like anything is changing. It actually is though - the timer will complete before the displayed time counts down to zero. To keep your time left display accurate, make sure to subtract the same amount from count as you are from repeatCount:

timer.repeatCount -= 300;
count -= 300;

Upvotes: 3

Related Questions