J2ME Countdown Timer

I'm working on a J2ME game that requires the use of a countdown timer. I've put in a Timer.scheduleAtFixedRate call inside my run() method, but apparently it's taking up a lot of resources and it's proceeding too fast (a 3-minute countdown will finish in about 30 seconds or less).
I have a separate method that calculates the amount of time left in terms of minutes and seconds, and the output will jump irregularly (say from 2:59 to 1:13 to 0:57, and so on).
Here's the piece of code in question:
    public void run() {
        Thread currentThread = Thread.currentThread();
        //timeLeftInMillis is an int
        timeLeftInMillis = 180000;
        try
            // This ends when myThread is set to null, or when
            // it is subsequently set to a new thread; either way, the
            // current thread should terminate.
            while (currentThread == myThread)
                //myTimer is a Timer object instantiated in the
                //constructor
                myTimer.scheduleAtFixedRate(new TimerTask () {
                    public void run(){
                        GameScreen.timeLeftInMillis=GameScreen.timeLeftInMillis-1000;
                        System.out.println(GameScreen.timeLeftInMillis);
                        if (GameScreen.timeLeftInMillis<= 0) {
                                synchronized (this) {
                                    GameScreen.isGameOver = true;
                                    this.cancel();
                }, 0, 1000L);
                repaint(0, 0, screenWidth, screenHeight);
                serviceRepaints();
        catch (Exception e)
    }Can anyone help me figure out what's wrong with this timer? Any help at all would be appreciated.
Thanks. :)

Problem solved. :)
Comments are welcome. :)
    public void run()
        int millis_per_tick = 100;
        int counter = 1000/millis_per_tick;
        timeLeftInMillis = 180000;
        Thread currentThread = Thread.currentThread();
        try
            // This ends when myThread is set to null, or when
            // it is subsequently set to a new thread; either way, the
            // current thread should terminate.
            while (currentThread == myThread)
                long startTime = System.currentTimeMillis();
                repaint(0, 0, screenWidth, screenHeight);
                serviceRepaints();
                long timeTaken = System.currentTimeMillis() - startTime;
                if (timeTaken < millis_per_tick)
                    synchronized (this)
                        wait(millis_per_tick - timeTaken);
                if (counter == 0) {
                    timeLeftInMillis = timeLeftInMillis - 1000;
                    counter = 1000/millis_per_tick;
                else
                    counter--;
                if (timeLeftInMillis<0) {
                    synchronized(this){
                        isGameOver = true;
        catch (InterruptedException e)
    }

Similar Messages

  • Visual Countdown Timer

    I'm working on my first J2ME project, and I'm trying to figure out how best to create a visual countdown timer. In this application, the user is given a little 'mission' that must be solved. Some missions are timed, and the device must be able to display how much time is left in the mission.
    I need the timer to stay on the screen (preferrably the top) even though the user may be scrolling through text to be read, or even making selections (List, Choice, or Textfields). Basically, think of the Ticker (from the bundled Stocks demo), but instead of scrolling static text continuously, I want it to display a timer, countling down from some time (e.g. 10 minutes) and updating (9:59, 9:58, ..., 0:03, 0:02, 0:01) fairly frequently (if not every second).
    Is the source to the Ticker 'widget' available someplace?
    Also, does anyone have any suggestions how to best do this keeping resource usage as low as possible???
    Thanks in advance,
    Christian ([email protected])

    hmm, always visible...
    you could try removing/adding a Command once a second, with its label as the time ;]
    pretty ugly way of doing it, but the only way if your dealing with Form's.
    rob,

  • Best way to implement a countdown timer for a turn based LCCS game

    Hello,
    I am trying to build a turn based game and sketching out the high level map, so I can focus my efforts towards the direction I should be digging.
    One thing I have not seen much in the sample apps is how a turn based game is best handled.
    For example, a countdown timer. Should it be a shared property? Or a Baton which is supposed to manage workflows and has a timeout property?
    Or, should I forget those two, and time this on the server, although if it would become popular keeping track of all the times in the rooms would cost an arm and leg. Would love to hear some best practices on this.

    good idea.
    Which one or all of them?
    Once you eliminate the impossible, whatever remains, no matter how improbable, must be the truth. - "Sherlock holmes" "speak softly and carry a big stick" - theodore roosevelt. Fear leads to anger, anger leads to hate, hate leads to
    suffering - Yoda. Blog - http://www.computerprofessions.co.nr

  • How can I make a countdown timer using After Effects

    I'd like to make a video that has a timer that counts down one second at a time. I need one starting at 5:00 (five minutes). Is there a way to easily do this in After Effects without having to manually change the text every second?
    Thanks.

    I'm glad that you found a solution, but I thought that you might appreciate a suggestion of another approach.
    Colin Braley provides a tutorial and example project on
    his website that show how to use an expression on the Source Text property to animate text to overcome some of the limitations of the Numbers effect.
    There's a similar example in the
    "Example: Animate text as a timecode display" section of After Effects Help.
    Here are some Community Help searches that can lead you to some ideas, too:
    Community Help search for 'countdown timer'
    Community Help search for 'digital countdown timer'

  • Countdown Timer Error Msg: "Warning: 1090: Migration issue"

    Hey folks,
    New to Flash here (using CS3), trying to create a countdown
    timer.
    Following is the error message I receive when trying to test
    the
    movie:
    "Warning: 1090: Migration issue: The onEnterFrame is not
    triggered
    automatically by Flash Player at run time in ActionScript
    3.0. You
    must first register this handler for the event using
    addEventListener
    ( 'enterFrame', callback_handler).
    Does anyone know what this means? And please "dumb it down"
    for this newbie. :)
    Following is the actionscript I'm using:
    this.onEnterFrame = function() {
    var today:Date = new Date();
    var currentYear = today.getFullYear();
    var currentTime = today.getTime();
    var targetDate:Date = new Date(2007,5,10);
    var targetTime = targetDate.getTime();
    var timeLeft = targetTime - currentTime;
    var sec = Math.floor(timeLeft/1000);
    var min = Math.floor(sec/60);
    var hrs = Math.floor(min/60);
    var days = Math.floor(hrs/24);
    sec = String(sec % 60);
    if (sec.length < 2) {
    sec = "0" + sec;
    min = String(min % 60);
    if (min.length < 2) {
    min = "0" + min;
    hrs = String(hrs % 24);
    if (hrs.length < 2) {
    hrs = "0" + hrs;
    days = String(days);
    var counter:String = days + ":" + hrs + ":" + min + ":" +
    sec;
    time_txt.text = counter;
    Thanks in advance!!!

    It just means that you can't do things the "old" way. You
    have to use the
    AS3 event model, like so:
    this.addEventListener("enterFrame", enterFrameHandler);
    function enterFrameHandler(evt:Event) {
    var today:Date = new Date();
    var currentYear = today.getFullYear();
    var currentTime = today.getTime();
    var targetDate:Date = new Date(2007,5,10);
    var targetTime = targetDate.getTime();
    var timeLeft = targetTime - currentTime;
    var sec = Math.floor(timeLeft/1000);
    var min = Math.floor(sec/60);
    var hrs = Math.floor(min/60);
    var days = Math.floor(hrs/24);
    sec = String(sec % 60);
    if (sec.length < 2) {
    sec = "0" + sec;
    min = String(min % 60);
    if (min.length < 2) {
    min = "0" + min;
    hrs = String(hrs % 24);
    if (hrs.length < 2) {
    hrs = "0" + hrs;
    days = String(days);
    var counter:String = days + ":" + hrs + ":" + min + ":" +
    sec;
    time_txt.text = counter;

  • Javascript countdown timer not working in Safari

    Years ago I copied a Javascript for a countdown timer and it has been working on my website ever since in both Safari and Firefox. I have been working on updating my site and suddenly it stopped working in Safari, but still works in Firefox. Obviously, I'd like it to work in everyone's browser if possible. I've created a page which only has the countdown timer on it. Can anyone tell me what I need to do to get it to work in Safari?
    The test page where you can see this is: http://hyperflite.com/countdowntest.html
    TIA

    Hi,
    Is there any reason for the numerous body tags in there?
    <pre><body onload="doCountdown();">
    <body>
    <body ... >
    </pre>
    I don't have Safari here to test with, but I wouldn't have thought they were helping matters

  • 5 minute countdown timer with 3d extrusion  for AE CC  5:00

    dear  AE  Family,
    Total Newbie here  looking to make a 3d countdown timer in  after effects  CC.  I know how to use the effect  to make the standard timer.  But I want to make the
    3d extrusion  5:00 which looks much better.  My CC came with  cinema 4d  lite but cant seem to put them together. 
    PS  I really need it to look like  5:00  4:59,   to 0:00 . 3d extrusion.
    Thanks in advance, much appreciated.

    Have you gone though Getting Started with After Effects?
    Have you seen the Basic Workflow series?
    Be aware that if you want extruded text with Ray-traced rendering you are going to be in for long render times even with a compatible Cuda card installed and extremely long render times without one.
    The easiest way to make a countdown timer that will work with extruded text is to Google Countdown Timer After Effects and then look for expressions. You will find this popular universal timer expression from Dan Ebberts: Dan Ebberts's Expressioneering Design Guide
    Get that far and get back to us with your problems.
    BTW, there are other ways to mimic 3D extrusions and simple layer effects like Bevel and Emboss or the effect Bevel Alpha that may meet your design idea.

  • How can I create an animated countdown timer?

    Is there a way to create an animated countdown timer in Adobe Fireworks (animated gif)?
    Thank you

    In the Edit workspace, place the images you want to appear in each frame of the animation on separate layers of the Layers panel. For example, to create an animation of an eye blinking, you would place an image of the open eye on one layer, and an image of the closed eye on another layer.
    Choose File > Save for Web.Note: If your image has multiple layers, you can also open the Save For Web dialog box from the Save As dialog box by choosing CompuServe GIF Format and selecting Layers As Frames.
    Optimize the image in GIF format.
    Select Animate.
    Set additional options in the Animation section of the dialog box:
    Loop Continuously repeats the animation in a web browser.
    Frame Delay Specifies the number of seconds that each frame is displayed in a web browser. Use a decimal value to specify fractions of a second. For example, use .5 to specify half a second.

  • How to implement countdown timer in apex

    Hi all,
    I want to implement timer in my application.i am working on apex 4.0 version.I am developing online test application,so for this i want to display timer for test.
    can anyone suggest me how can i implement countdown timer in my application.
    thanks
    jitu

    Hi,
    You can refer "Martin Giffy D'Souza's" Enhanced APEX Session Timeouts example
    http://www.talkapex.com/2009/09/enhanced-apex-session-timeouts.html
    Regards,
    Kartik Patel
    http://patelkartik.blogspot.com/
    http://apex.oracle.com/pls/apex/f?p=9904351712:1

  • How to develop a countdown timer in jsp

    Hi all, please i have an online test application that works but i want to include a countdown timer that redirects to another page when the time runs out. please, how do i go about it. please help

    Thanks, but thats not the one i need. i want the one that will show the time in hh:mm:ss and then automatically take the user to the result page when the time i up. i have a javascript code i used but the problem is in the Result.jsp page, there are some parameters that are suppose to be passed but i dont know how to do it. this is the code:
    <form name="frm2" method="post">
    <script language="javascript">
    var sec = 10;   // set the seconds
    var min = 00;   // set the minutes
    var targetURL="result.jsp"; //the url
    var email=this.Field('email').value;
    function countDown() {
      sec--;
      if (sec == -01) {
        sec = 59;
        min = min - 1;
      } else {
       min = min;
    if (sec<=9) { sec = "0" + sec; }
      time = (min<=9 ? "0" + min : min) + " min and " + sec + " sec ";
    if (document.getElementById) { theTime.innerHTML = time; }
      SD=window.setTimeout("countDown();", 1000);
    if (min == '00' && sec == '00') { sec = "00"; window.clearTimeout(SD);
    window.location=targetURL;
    function addLoadEvent(func) {
      var oldonload = window.onload;
      if (typeof window.onload != 'function') {
        window.onload = func;
      } else {
        window.onload = function() {
          if (oldonload) {
            oldonload();
          func();
    addLoadEvent(function() {
      countDown();
    </script>
    <table width="100%">
    <tr><b><td width="100%" align="center"><span id="theTime" class="timeClass"></span></td></b></tr>
    </table>
    </form>and this is are the fields needed in the Result.jsp page..
    <input type="hidden" name="email" value=<%=exno%> />
    <input type="hidden" name="dbase" value=<%=names%> />
    <input type="hidden" name="tamt" value=<%=total%> />

  • How do i add a countdown timer in as3 that starts when the program begins?

    I also want it to remove everything that is on the stage when it reaches 0 and produce a Game Over screen.

    import flash.events.TimerEvent;
    import flash.utils.Timer;
    var countdown:Timer = new Timer (1000,TARGET_TIME);
    //after 60 Seconds every DisplayObject will be removed from stage
    const TARGET_TIME:int = 60;
    countdown.addEventListener(TimerEvent.TIMER, tick);
    countdown.addEventListener(TimerEvent.TIMER_COMPLETE, gameOver);
    function tick(e:TimerEvent):void {
        //this will count upwards 1.2.3.4....
        trace(e.currentTarget.currentCount);
    function gameOver(e:TimerEvent):void {
        // this function will remove all DisplayObjects from your Stage
        // starting from the top
        //It will not remove shapes or anything the user might have drawn on the stage
        //just things that are accessible to ActionScript (Sprites, MovieClips)
        for (var i:int = this.numChildren-1 ; i >= 0; i--) {
            removeChildAt(i);
    //countdown will start only if you call it explicitly
    countdown.start();

  • How to create countdown timer with sound

    Any ideas on how to create a minute and seconds countdown timer that would play a sound and then redirect you to another page?

    Hi,
    There is no out of the box solution to do so in Muse at the moment. If you can get your own code, you can add it to your site using "Insert HTML" feature.
    Regards,
    Aish

  • Need help on countdown timer!

    Could someone please guide me in the direction as to how to make a countdown timer?  I created a timer that counts down to a certain date, but I just want the timer to countdown 24 hours, not to a certain date.  I also want to have a button below the timer so that when you click it, it adds 30 seconds to the timer.  Can anyone help me with this?

    Hi,
    I hope it will be use full for u....
    var timelong=2000;
    var mytimer:Timer=new Timer(timelong,1);
    mytimer.addEventListener(TimerEvent.TIMER_COMPLETE,myfunc);
    mytimer.start();
    function myfunc(event:TimerEvent)
        trace("hi it's working");
    mybut.addEventListener(MouseEvent.CLICK,addtime);
    function addtime(event:MouseEvent)
        timelong+=3000;
    Thanks,
    K Swamy Vishnubhatla,

  • Countdown Timer

    Can anyone gve me any advice on how to make a countdown timer
    in actionscript 3?
    I have tried several ways and have so far been
    unsucessful.

    Here's something simple:
    var endDate:Date = new Date(2012, 11, 21);
    var t:Timer = new Timer(500);
    t.addEventListener(TimerEvent.TIMER, msLeft);
    t.start();
    function msLeft(e:TimerEvent){
    var now:Date = new Date();
    var ms = endDate.valueOf() - now.valueOf();
    var secs = Math.floor((ms / 1000) % 60);
    var mins = Math.floor((ms / 1000 / 60) % 60);
    var hours = Math.floor((ms / 1000 / 60 / 60) % 24);
    var days = Math.floor((ms / 1000 / 60 / 60 / 24) % 365);
    var years = Math.floor(ms / 1000 / 60 / 60 / 24 / 365);
    trace(years, "years", days, "days", hours, "hours", mins,
    "minutes", secs,
    "seconds");
    Dave -
    www.offroadfire.com
    Head Developer
    http://www.blurredistinction.com
    Adobe Community Expert
    http://www.adobe.com/communities/experts/

  • Countdown timer to NEXT WHOLE HOUR..?

    Hello.
    I need to create a countdown timer function.
    Normally that would not be a problem for me, but this timer needs to countdown to the next whole hour. As an example, if the time is 23:42 the countdown would say 17:35 (17 minutes, 35 seconds).
    When the timer hits zero, it will start from 59:59 and so on.. Always counting to the next whole hour.
    Im kind of in a jam and need this done ASAP, any help would be greatly apreciated!
    / Rasmus

    Im sorry if i implied that im a great actionscripter, im not
    What i would normally do is just grab a counter script from a google search and modify it to countdown to the correct time, but i havent been able to find a counter that counts down to the next whole hour.
    It should just be plain and simple and display the time in minutes and seconds like this: 25:14
    I found this one on google, counting down for christmas. If that could be modded into showing only minutes and seconds and of course counting down to the next whole hour, that would be awsome!
    https://dl.dropbox.com/u/2628604/countdown-test.fla

Maybe you are looking for

  • IPad iOS 5 upgrade saying it will wipe all apps and settings

    I have a 3GS and a 1st gen iPad.  Both the iPhone and iPad were sync'd to the same PC.  The iPad has only ever been sync'd to this PC. I've upgraded the 3GS to iOS 5 with minimal issues (just took 6 tries and a long time), but it's up and running fin

  • Can't get FaceTime to work

    Can't get face time to work

  • How do I convert a microsoft word document to a pdf?

    I need help to submit an assignment for school but I can't figure out how to convert word to a pdf.  My old computer was easy.  All I had to do was right click and convert, not with this computer. Can anyone shed some light? Thank you

  • IPhone 4 crackling and grainy white noise!!??

    I have recently had my iPhone 4 replaced because of terrible noise interference during calls to the point where the sound totally went off....I have had my new iPhone 4 for 3 weeks, last week it started to make funny noises! Really loud crackling dur

  • Need table name for email id

    Hi experts, I got employee id BNAME from table crmd_orderadm_i. Based on that field i need to get the Email ID for that user. Can anyone please tell me the table where it is stored in. regards, venkatesh.