Search code examples
javaclocknanotime

Slow down a clock based on System.nanoTime();


I have a timer based on System.nanoTime() and I want to slow it down.

I have this:

elapsed = System.nanoTime();
seconds = ((elapsed -  now) / 1.0E9F);

where now is System.nanoTime(); called earlier in the class.

In order to slow it down I tried:

if(slow){
    elapsed = System.nanoTime();
    seconds = ((elapsed -  now) / 1.0E9F) * 0.5F;
}else{//The first code block

But then I run into the problem of seconds being cut in half, which is not desirable. Before slow is true, it's displaying 10 seconds to the screen, and when slow is true, it displays 5 seconds, which is not desirable.

I want to slow the timer, not cut it in half as well as slow it down

On the other hand, it slows down the time, which is what I want.

How would I slow down the time, without cutting my existing time in half?


Solution

  • Add to seconds rather than recalculating it from scratch each time through the loop:

    elapsed = System.nanoTime();
    if (slow) {
        seconds += ((elapsed -  now) / 1.0E9F) * .5F;
    }
    else {
        seconds += ((elapsed -  now) / 1.0E9F);
    }
    now = elapsed;  // so next time you just get the incremental difference