Search code examples
javajava-threadssystem.out

Java: Printing to screen is delayed


So I have a function that is supposed to print out text like it is being typed onto the screen.

I tried setting and getting the time it took to print to the screen using System.nanoTime(), and removing that from Thread.sleep, but it was still not smooth.

I would like for each letter to be printed and take roughly the same amount of time, instead of jerking back and forth between letters like it currently does.

public static void slow_print(String to_print) {
    long time_between = 200;
    for (int i = 0; i < to_print.length(); i++) {
        System.out.print(to_print.charAt(i));
        try {
            Thread.sleep(time_between);
        }
        catch(InterruptedException event) {
            System.out.println("Not supposed to happen");
        }

    }
    System.out.println();
}

Solution

  • Output is bufferized. To flush buffer you need to call flush or include \n into your string.