How to gradually count down to zero over a changeable duration in Java?

I have a timer of X seconds, and I want Y to count down to zero in even spaces of time, reaching 0 at the same time the timer finishes.

For example, If I had a timer of 10 seconds, and a value of 20, I would want the value to go down by 2 every second.

The timer would preferably update quickly as it will be displayed as a bar.

Thank you for your help!

For context, here is the timer I am using:

public EventTimer(int seconds) {
        // Start timer
        timer = new Timer();
        timer.schedule(new RemindTask(), seconds*1000);
        cooledDown = false;
    }

    class RemindTask extends TimerTask {
        public void run() {
            // Ends timer
            timer.cancel(); //Terminate the timer thread
            cooledDown = true;
        }
  • Roman

Edit: I know that I could just set another timer but my main goal here is to decrement gradually

Answer

i came up with this.

public class HelloWorld {

    public static void main(String[] args) {

        int seconds = 5;
        int value = 10;
        TimerThatDoesntRequireThreadedProgramming(seconds, value);

    }

    // Checkmate Java Threaded Programming
    public static void TimerThatDoesntRequireThreadedProgramming(double seconds, double value) {

        double ms = (double) seconds * 1000;
        double val = value * 1000;

        if (ms < 0) {
            return;
        }

        double s = System.nanoTime();

        double lerpTime = 1000 / (val/ms);

        int counter = 0;

        while ((double) (System.nanoTime() - s) / 1000000 < ms) {

            if((double) (System.nanoTime() - s) / 1000000 > lerpTime) {
                System.out.println(counter);
                counter++;
                lerpTime += 1000 / (val/ms);
            }
        }

        System.out.println("Done! Counted to " + value + " in " + seconds + " seconds :D");
        return;
    }
}

It is just a regular timer using nanotime (not recommended i know) but contains a lerping function.

lerpTime = 1000 / ( value / seconds );

So normaly lerpTime is increased by 1000 every time to count and output the seconds in real second steps but in this example with counting to 10 in 5 seconds the lerpTime time will be the half of it (500).

Leave a Reply

Your email address will not be published. Required fields are marked *