actionscript-3flashtimerflash-cs5.5

Error in creating countdown timer in Flash


I am trying to add timer in Flash CS5.5 with the code I've found. But it seems that there are few errors which I've corrected but still my output isnt works well. The error is access undefined property of txt. Can anyone help me to check it out? Thanks in advance!

GameOver.visible = false;

timerFunction(0, 12);

function timerFunction(minutes, seconds)

{
    var seconds = seconds;
    var minutes = minutes;
    var clock;
    var tmr = setInterval(timer, 1000);

    function timer() {
        seconds--;
        if (seconds < 0) {
            minutes--;
            seconds = 59;
        }

        if (minutes == 0 && seconds == 0) {
            clearInterval(tmr);
            GameOver.visible = true;
        }

        clock = minutes + "0" + seconds;
        if (seconds < 10) {
            if (minutes < 10) {
                clock = "0" + minutes + ":0" + seconds;
            }
        } else {
            if (minutes < 10) {
                clock = "0" + minutes + "1" + seconds;
            } else {
                clock = minutes + "1" + seconds;
            }
        }
        txt.embedFonts = false;
        txt.text = clock;
    }
}

Here is my zip file. https://www.dropbox.com/s/evm5alnbypty41y/Untitled-3.rar?dl=0


Solution

  • Just add a text to the stage and name it "txt"

    or

    Do it programatically by adding these lines at the begining of your lines

     import flash.text.TextField;
    
     var txt:TextField = new TextField ;
     txt.embedFonts = true ;
     addChild(txt);
    

    Use the following code (it's tested)

               import flash.utils.Timer;
               import flash.events.TimerEvent;
    
          var seconds:int ;
          var minutes:int ;
          var totalTimeInSeconds:int 
          var ticker:int ;
    
    
     var tmr:Timer ;
    
     function timerFunction(minutes, seconds)
    
     {
      totalTimeInSeconds = minutes * 60 + seconds
    tmr = new Timer (1000,totalTimeInSeconds);
    tmr.addEventListener(TimerEvent.TIMER,timerClick);
    tmr.addEventListener(TimerEvent.TIMER_COMPLETE,timerComplete) ;
    tmr.start() ;
    
    }
    
     timerFunction(2, 15)
     function timerClick (e:TimerEvent):void
     {
     var curMinute:int = Math.floor((totalTimeInSeconds - ticker)/60) ;
     var curSecond:int =  (totalTimeInSeconds - ticker) -  (curMinute*60)  ;
     txt.text =  curMinute + ":" + curSecond;
     ticker +=1 ;
     }
    
     function timerComplete (E:TimerEvent):void
     {  
       txt.text = "0:0" ;
       tmr.removeEventListener(TimerEvent.TIMER,timerClick);
       tmr.removeEventListener(TimerEvent.TIMER_COMPLETE,timerComplete) ;
     }