I'm watching a video on regulating frames per second. I don't really fully understand the code.

public void run() {
    long lastTime = System.nanoTime();
    final double ns = 1000000000.0 / 60.0;
    double delta = 0;

    while(running) {
        long now = System.nanoTime();
        delta += (now - lastTime) / ns; // <--This line is confusing me.
        lastTime = now;                 //  Why is this divided by "ns"?
        while(delta >= 1) {


1 Answer 1


Assuming the 60 is referring to the desired frames per second, the line

delta += (now - lastTime) / ns

is calculating, from the change in time, the amount of frames to process. ns contains the desired frequency (in nanoseconds) which is equivalent to 1 second per 60 frames. Dividing the change in time by this factor results in the conversion of nanoseconds to seconds and the amount of frames needed to calculate to 'catch up.'

For example, if 0.3 seconds had passed, you would need to process 0.3 seconds * 60 frames per second = 18 frames.

If the math is confusing at all, I suggest writing it out with the units to see how it works.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .