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

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.

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;

Related

AS3 How to Set Up A Max Time Count Up

I have the following count up code, but am not sure how I would be able to include an if else statement to have the count-up stop at 15 seconds for example.
Here is the code:
var timer:Timer = new Timer(100);
timer.start();
timer.addEventListener(TimerEvent.TIMER, timerTickHandler);
var timerCount:int = 0;
function timerTickHandler(Event:TimerEvent):void{
timerCount += 100;
toTimeCode(timerCount);
}
function toTimeCode(milliseconds:int) : void {
//create a date object using the elapsed milliseconds
var time:Date = new Date(milliseconds);
//define minutes/seconds/mseconds
var minutes:String = String(time.minutes);
var seconds:String = String(time.seconds);
var miliseconds:String = 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
timer_txt.text = minutes + ":" + seconds+"." + miliseconds;
}
First, for efficiency, you can use the timers built in currentCount property to know how much time has elapsed (instead of making a timerCount var to that end)
To stop the timer after 15 seconds, simply set the appropriate repeat count so it ends at 15 seconds, or stop it in the tick handler after 15 seconds have past:
var timer:Timer = new Timer(100,150); //adding the second parameter (repeat count), will make the timer run 150 times, which at 100ms will be 15 seconds.
timer.start();
timer.addEventListener(TimerEvent.TIMER, timerTickHandler);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, timerFinished); //if you want to call a function when all done
function timerTickHandler(Event:TimerEvent):void{
toTimeCode(timer.delay * timer.currentCount); //the gives you the amount of time past
//if you weren't using the TIMER_COMPLETE listener and a repeat count of 150, you can do this:
if(timer.delay * timer.currentCount >= 15000){
timer.stop();
//do something now that your timer is done
}
}

Adding additional time to main timer from movieclip?

Hi so yeah in the main timeline I have the timer
var count:Number = 300;//Count down from 300
var myTimer:Timer = new Timer(1000,count);
myTimer.addEventListener(TimerEvent.TIMER, sayHello);
function sayHello(e:TimerEvent):void
{
trace("Current Count: " + myTimer.currentCount);
}
And when you go into the movieclip reimoi_mcand click the useplush button I want to be able to add additional seconds onto the timer. The following is the code in the reimoi_mc clip but yeah I really have no idea how to make this work, please help ;0; (I have to use MovieClip(root) to access the running timer from the main timeline within the movieclip)
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.utils.getTimer;
stop();
useplush.addEventListener(MouseEvent.CLICK, addtime);
function addtime(e:MouseEvent):void
{
MovieClip(root).count += 2;
MovieClip(root).myTimer.repeatCount += MovieClip(root).count; //add time to the timer
trace("new time " + myTimer.currentCount);
}
I think what you are trying to do is add 2 seconds to the timer in the click handler, and then show how much time is left? If so, just a couple tweaks will do:
function sayHello(e:TimerEvent):void {
trace("Time Left: " + myTimer.repeatCount - myTimer.currentCount); //time left is the repeat count - the current count
}
function addtime(e:MouseEvent):void {
MovieClip(root).myTimer.repeatCount += 2 //add 2 more ticks to the timer (currentCount will always remain the same unless the timer is reset)
trace("new time remaining: " + MovieClip(root).myTimer.repeatCount - MovieClip(root).myTimer.currentCount);
}
BONUS CODE!
If you wanted to make it agnostic of the timer delay (let's say you want it to update quicker than 1 second for instance), you could do this:
var startingTime:Number = 20; //the initial time in seconds
var myTimer:Timer = new Timer(200); //your timer and how often to have it tick (let's say 5 times a second)
myTimer.repeatCount = startingTime * Math.ceil(1000 / myTimer.delay); //set the initial repeat count
myTimer.addEventListener(TimerEvent.TIMER, sayHello);
myTimer.start();
function sayHello(e:Event):void {
trace("Time Left: " + ((((myTimer.repeatCount - myTimer.currentCount) * myTimer.delay) / 1000)) + "seconds");
}
And in your other object:
stage.addEventListener(MouseEvent.CLICK, function(e:Event){
myTimer.repeatCount += Math.ceil(2000 / myTimer.delay); //add 2000 milliseconds to the timer
});
You'd better use an external counter to count the time, instead of stuffing it into a Timer object. You would then need timers to measure delays, and listeners to count them.
var myTimer:Timer=new Timer(1000); // no second parameter
public var secondsLeft:int=300; // former "count"
myTimer.addEventListener(TimerEvent.TIMER, sayHello);
function sayHello(e:TimerEvent):void {
secondsLeft--;
trace("Seconds left:", secondsLeft);
if (secondsLeft<=0) {
myTimer.stop();
myTimer.reset();
// whatever else to trigger when time runs out
}
}
And then you just add to secondsLeft and update the scoreboard.

How to add seconds to Timer in AS3

Hey everyone So I have a countdown timer that I have managed to implement in my game that I saw on some forums. Now I set up a new function to add some seconds to the timer whenever the user Hittest with a Movie Clip but it doesnt seem to work right the errors I'm getting is while it does add more time, It's not really adding it because when i do add more time and say the timer counts down to 10 depending on how much more seconds I added with the Hittest the game ends on 10 rather than 0 seconds. So I don't think its actually changing the time interval internally.
Also when I restart the game it shows the past time for the one second interval then once it starts counting down it finally resets and starts counting down normally.
Here is how I have it setup:
My initialized variables in my constructor:
count = 30; //Count down from 60
myTimer = new Timer(1000, count);// Timer intervall in ms
myTimer.addEventListener(TimerEvent.TIMER, countdown);//EventListener for intervalls
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, countdownComplete);
myTimer.start();//start Timer
The countDown function:
private function countdown(e:TimerEvent):void
{
//Display Time in a textfield on stage
countDownTextField.text = String((count)- myTimer.currentCount);
updateCountdownTimer();
}
In my HitTest Function:
private function onPopIsClicked(pop:DisplayObject):void
{
nScore ++;
updateHighScore();
updateCurrentScore();
//Add Explosion Effect
popExplode = new mcPopExplode();
stage.addChild(popExplode);
popExplode.y = mPop.y;
popExplode.x = mPop.x;
elapsedTime += 5;
updateCountdownTimer();
}
Then finally in my updateCountdownTimer():
public function updateCountdownTimer():void
{
countDownTextField.text = String((count)- myTimer.currentCount + elapsedTime);
}
Can you see why I can't add more seconds to the timer correctly?
Thanks in advance.
**** UPDATE ******
count = 10; //Count down from 10
myTimer = new Timer(1000, count);// Timer intervall in ms
updateCountdownTimer();
myTimer.addEventListener(TimerEvent.TIMER, countdown);//EventListener for intervalls
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, countdownComplete);
myTimer.start();//start Timer
private function countdown(e:TimerEvent):void
{
//Display Time in a textfield on stage
updateCountdownTimer();
}
private function onPopIsClicked(pop:DisplayObject):void
{
elapsedTime += 2;
myTimer.repeatCount += elapsedTime; //add time to the timer
count += elapsedTime;
updateCountdownTimer();
trace("pop clicked and time");
}
public function updateCountdownTimer():void
{
countDownTextField.text = String((count)- myTimer.currentCount);
}
So the solution to add time to the Timer is to adjust the repeatCount property. You would do that in your onPopIsClicked():
private function onPopIsClicked(pop:DisplayObject):void
{
nScore ++;
updateHighScore();
updateCurrentScore();
//Add Explosion Effect
popExplode = new mcPopExplode();
stage.addChild(popExplode);
popExplode.y = mPop.y;
popExplode.x = mPop.x;
elapsedTime += 5;
myTimer.repeatCount += 5; //add time to the timer
updateCountdownTimer();
}
So you will need to change how you display your countdown since we are increasing the repeatCount property. What will happen is your myTimer.currentCount may increase past the size of your count variable. So in your onPopIsClicked() add this line after you increment elapsedTime:
elapsedTime += 5;
myTimer.repeatCount += 5;
count += 5//this line, increment the count total
You can also set a variable to increment by if you wanted:
var increaseBy:int = 5
Then you would use that with repeatCount, count, and elapsedTime (if you need that still):
elapsedTime += increaseBy;
myTimer.repeatCount += increaseBy;
count += increaseBy;
You really don't need elapsedTime anymore unless you are using it for something else. Then you update your text, there is no need to add the elapsedTime so it would look like:
countDownTextField.text = String(count- myTimer.currentCount);

Action Script 3. Timer MM:SS doesn't work

I'm creating app and I need to show game time MM:SS format. But I don't know why timer doesn't wrok It shows 0:00.359 (359 of miliseconds) and not change. Where is the problem? I can't find It. Thank you.
var timer:Timer; //import flash.utils.Timer;
var txtTime:TextField;
var tmpTime:Number; //this will store the time when the game is started
//your constructor:
public function MemoryGame()
{
timer = new Timer(1000); //create a new timer that ticks every second.
timer.addEventListener(TimerEvent.TIMER, tick, false, 0, true); //listen for the timer tick
txtTime = new TextField();
addChild(txtTime);
tmpTime = flash.utils.getTimer();
timer.start(); //start the timer
//....the rest of your code
}
private function tick(e:Event):void {
txtTime.text = showTimePassed(flash.utils.getTimer() - tmpTime);
}
//this function will format your time like a stopwatch
function showTimePassed(startTime:int):String {
var leadingZeroMS:String = ""; //how many leading 0's to put in front of the miliseconds
var leadingZeroS:String = ""; //how many leading 0's to put in front of the seconds
var time = getTimer() - startTime; //this gets the amount of miliseconds elapsed
var miliseconds = (time % 1000); // modulus (%) gives you the remainder after dividing,
if (miliseconds < 10) { //if less than two digits, add a leading 0
leadingZeroMS = "0";
}
var seconds = Math.floor((time / 1000) % 60); //this gets the amount of seconds
if (seconds < 10) { //if seconds are less than two digits, add the leading zero
leadingZeroS = "0";
}
var minutes = Math.floor( (time / (60 * 1000) ) ); //60 seconds times 1000 miliseocnds gets the minutes
return minutes + ":" + leadingZeroS + seconds + "." + leadingZeroMS + miliseconds;
}
//in your you-win block of code:
var score = flash.utils.getTimer() - tmpTime; //this store how many milliseconds it took them to complete the game.
Try
timer.currentCount
instead of
flash.utils.getTimer()
It will return the number of times the timer has fired the TIMER-Event.
You need not do this.
var time = getTimer() - startTime;
In your code, startTime is already time elapsed due to
showTimePassed(flash.utils.getTimer() - tmpTime);
OR
you can call
showTimePassed();
and change time calculation as
var time = getTimer() - tmpTime;

How do you stop setInterval() after certain number of iterations

I have tried following code and its working but how do i stop when its reach 130 ?
var textValue:Number = 67.1;
var addValue:Number = .1;
my_txt.text = textValue.toString();
function counter(){
textValue += addValue;
my_txt.text = textValue.toString();
}
setInterval(counter, 10);
setInterval returns a unique ID as an unsigned int (uint). You can use clearInterval with this ID to stop the interval. The code:
var textValue:Number = 67.1;
var addValue:Number = .1;
var myInterval:uint;
function counter(){
textValue += addValue;
my_txt.text = textValue.toString();
if( textValue >= 130 ) {
clearInterval(myInterval);
}
}
myInterval = setInterval( counter, 10 );
You can stop an interval by using clearInterval. Try this:
var textValue:Number = 67.1;
var addValue:Number = .1;
my_txt.text = textValue.toString();
function counter(){
textValue += addValue;
my_txt.text = textValue.toString();
//check for end value
if (textValue>=130)
{
//clear the interval
clearInterval(intervalID);
}
}
//store the interval id for later
var intervalID:uint = setInterval(counter, 10);
Since it seems like you may be using actionscript 3, I suggest not using an interval at all. A Timer object may be better as it can offer better control, such being able to set the number of times it fires off before stopping itself and being able to easily start, stop, and restart the timer as needed.
Example of using a Timer object and adding an event listener for each tick
import flash.utils.Timer;
import flash.events.TimerEvent;
// each tick delay is set to 1000ms and it'll repeat 12 times
var timer:Timer = new Timer(1000, 12);
function timerTick(inputEvent:TimerEvent):void {
trace("timer ticked");
// some timer properties that can be accessed (at any time)
trace(timer.delay); // the tick delay, editable during a tick
trace(timer.repeatCount); // repeat count, editable during a tick
trace(timer.currentCount); // current timer tick count;
trace(timer.running); // a boolean to show if it is running or not
}
timer.addEventListener(TimerEvent.TIMER, timerTick, false, 0, true);
Controlling the timer:
timer.start(); // start the timer
timer.stop(); // stop the timer
timer.reset(); // resets the timer
Two events it throws:
TimerEvent.TIMER // occurs when one 'tick' of the timer has gone (1000 ms in the example)
TimerEvent.TIMER_COMPLETE // occurs when all ticks of the timer have gone (when each tick has happened 11 times in the example)
API Documentation: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/Timer.html