How do you fix a game loop flaw?

Here’s my current game loop code I’m using in my WIP project.



		while (running) {
			shouldRender = false;
			long now = System.nanoTime();
			unprocessed += (now - lastTime) / nsPerTick;
			lastTime = now;
			
			while (unprocessed >= 1) {
				tick++;
				unprocessed -= 1;
			}
			
			//Limits the number of ticks per unprocessed frame.
			int toTick = tick;
			if (tick > 0 && tick < 3)
				toTick = 1;
			if (tick > 7)
				toTick = 7;
			
			for (int i = 0; i < toTick; i++) {
				tick--;
				tick();
				shouldRender = true;
			}
			
			if (shouldRender) {
				frames++;
				render();
			}
			
			try {
				Thread.sleep(1);
			}
			catch (InterruptedException e) {
			}
			
			if (System.currentTimeMillis() - lastTimer > 1000) {
				lastTimer += 1000;
				fps = frames;
				System.out.println("FPS: " + Integer.toString(fps));
				frames = 0;
			}
		}

The flaw for this game loop is when the user is not focused on the Java application, the unprocessed ticks will incrementally go up until it gets refocused. When this happens, tick counts will briefly speed up about %300 or so until it throttles back down to normal.

How do I fix this flaw?

Your game loop doesnt include any sort of Limiting variable, so yes, you will get faster frame speeds at certain times. Here is an example game loop I used before which includes a limit.

public void run() {
        init();        
        double previously = System.nanoTime();
        double limit = 1000000000 / 20D; 
        double timer = 0;

        while (running) {
            double now = System.nanoTime();
            //Get the elapsed time since last cycle
            double whileElapsed = (now - previously);
            previously = now;

            timer += whileElapsed; // Add the elapsed time to our timer

            //Has it been more than our time limit?
            if (timer >= limit) {

                gsm.getCurrentGameState().Tick();
                

                //To make sure we never get periods of very fast
                while (timer >= limit) {
                    //Ticking, should the app run slower than our limit
                    timer -= limit;
                }
            }
            render();
        }
        stop();
    }