Search code examples
actionscript-3

How to keep timer running when i go to the other frame Actionscript 3.0


I am new to actionscript. I want to know how to run timer class and keep running even when i go to other frame. For example. I run timer in frame 2 and when i go to frame 1 timer keeps running, until i go back to frame 2 to stop the timer. I appreciate the help.

UPDATE : I try to make a stopwatch with these code :

var sec,min,hr:uint = 0;
sec_txt.text = min_txt.text = hr_txt.text = "00";
var timerStopWatch:Timer = new Timer(1000);
timerStopWatch.addEventListener(TimerEvent.TIMER, timerHandler);
function timerHandler(e:TimerEvent){
    var sec:String = String(uint(timerStopWatch.currentCount%60));
    var min:String = String(uint((timerStopWatch.currentCount/60)%60));
    var hr:String = String(uint((timerStopWatch.currentCount/60)/60));

    sec_txt.text = (uint(sec)< 10) ? "0" + sec:sec;
    min_txt.text = (uint(min)< 10) ? "0" + min:min;
    hr_txt.text = (uint(hr) < 10) ? "0" + hr:hr;
}

When i start the timer it work, but when i go to the second frame or another it stop and show a output error :

TypeError: Error #1009: Cannot access a property or method of a null object reference.

    at Stopwatch_fla::MainTimeline/timerHandler()
    at flash.utils::Timer/_timerDispatch()
    at flash.utils::Timer/tick()

What i want is, when i start the Timer and go to the other frame it will still running(ticking) and when i go back to the Timer frame i could stop it.


Solution

  • First, if you're going to be re-visiting the frame where your posted code lives, you want to make sure that timer doesn't get re-created every time and cause a memory leak.

    Change the following line

    var timerStopWatch:Timer = new Timer(1000);
    

    To these two lines:

    var timerStopWatch:Timer;
    if(!timerStopWatch) timerStopWatch = new Timer(1000);
    

    This will ensure your timer is only created once. That event listener will keep the timer in memory, so if you're constantly creating new timers and adding a listener to them, they will all stay in memory and your application will get slower and slower.

    Second, make sure you clean up after yourself.

    When you want your timer to be gone, stop it, remove the event listener and null the reference:

    timerStopWatch.stop();
    timerStopWatch.removeEventListener(TimerEvent.TIMER, timerHandler);
    timerStopWatch = null;
    

    Third, if your going to have this object span multiple frames, anything that is referenced in the event handler needs to persist in those frames as well.

    That means:

    sec_txt
    min_txt
    hr_txt
    

    All have to exist on any frame where this timer is running. Make sure on those frames that they have their instance names set properly.

    OR, check if they exist prior to using them:

    if(sec_txt) sec_txt.text = (uint(sec)< 10) ? "0" + sec:sec;