# How to sleep for the desired duration between game loop iterations?

My game loop below doesn't sleep as log as it should. The delta value always ends up less than 1, when it's supposed to be 16.6666 or close to 16.6666

double targetTime = 1000.0 / 60.0;//1000 millisecunts / 60 fps
long startTime;
long endTime = System.currentTimeMillis();
long delta;

long timer = System.currentTimeMillis();
int frameCount = 0;
while(running){
startTime = System.currentTimeMillis();
delta = startTime - endTime;
endTime = startTime;

tick(delta);
render();
frameCount +=1;

if(System.currentTimeMillis() - timer >= 1000){
System.out.println("Rendered frames: " + frameCount);
}
}


2) To fix the time delta accounting bouncing around, you can make a small adjustment and avoid calculating the sleep relative to the previous frame's time: instead of sleep(targetTime - delta), which is a measure of "how close the current frame follows the previous frame", you could use sleep(startTime + targetTime - System.currentTimeMillis()) which is a measure of "how long until the desired next frame from the current frame."
3) There's still a few issues with running your game logic (tick) at a variable frame rate based on the rendering speed, including drift over time due to the imprecision of Thread.sleep, and unstable behavior due to variable time steps, things can feel "higher friction" or glitch through/blow up when frame rate is too high or too low. You'll probably want to switch to a fixed-timestep loop (there are many resources on the internet, one popular one is at https://gafferongames.com/post/fix_your_timestep/) to get more stable simulation behavior.