# Java Interval

## Foreword

The Interval class will help us to measure time differences. We can (for example) use it very easily to find out how much time is left until a hero respawns after death or to find out how long a certain algorithm takes to execute.

Example:

`Interval i = new Interval();`

myAlgorithm();

System.out.println("it took: " + i.value() + " ms")

// => it took 5 ms (etc.)

## About System.currentTimeMillis()

The Java function System.currentTimeMillis() returns how long the system was running in milliseconds. Now if we do that once, wait a while, do it again and then subtract both results, we can easily measure time differences.

Example:

`long start = System.currentTimeMillis();`

myAlgorithm();

long elapsed = System.currentTimeMillis() - start;

System.out.println("It took " + elapsed + " ms");

## Implementation

We want to use the above method and put it all into a simple class that does all the calculations for us. The Interval class will start counting the time when it was created and the **.value()** function will always return how much time has elapsed since start. In addition, we will also implement a **.reset()** function to restart the time counter.

`public class Interval { `

long m_start = System.currentTimeMillis();

public long value() {

return System.currentTimeMillis() - m_start;

}

public void reset() {

m_start = System.currentTimeMillis();

}

}

*Note that m_start is being set when the object is created.*

## Usage Examples

In the first usage example we want to call the doStuff() function a few times, but only until 50 milliseconds are elapsed:

`Interval i = new Interval();`

// Do something for not longer than 50 milliseconds

while (i.value() < 50) {

doStuff();

}

The second example shows how the respawn problem mentioned above could be implemented with the Interval class:

`Interval respawnInterval = null;`

void playerTryToRespawn()

{

// 10 seconds elapsed already?

if (respawnInterval.value() >= 10000) {

// respawn

}

}

## Summary

A clean and simple implementation to solve a common problem when making games.