Search code examples
actionscript-3flashtimeractionscript-2countdown

Restarting timer in action script 3 function resetClock


I'm new to action script 3 so i will be picking your brains I lot.

I'm making a simple 5 min scoreboard for my workplace to use and now im stuck on making the reset button work.

I have made 3 buttons with instance of (start-btn, stop_btn and reset_btn) but I can't figure out the function code for the reset_btn. I need it to go back to 5:00 and stop so you can press start and begin counting from (5:00 or in my case 300) again.

This is my code so far:

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


var timeRemaining:int = 300;

showTime.text = formatTimeRemaining();

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

timer.stop();


start_btn.addEventListener(MouseEvent.CLICK, startClock);

function startClock(event:MouseEvent):void
{
timer.start();
}


stop_btn.addEventListener(MouseEvent.CLICK, stopClock);

function stopClock(event:MouseEvent):void
{
timer.stop();
}


reset_btn.addEventListener(MouseEvent.CLICK, resetClock);

function resetClock(event:MouseEvent):void
{
timer.reset();
showTime.text = "300";
}

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!");
}

Solution

  • function resetClock(event:MouseEvent):void
    {
        timer.stop();
        timeRemaining = 300;
        showTime.text = formatTimeRemaining();
    }
    

    Simply stop the timer, reset the timeRemaining variable then display it.