phplocalhostusleep

usleep() on localhost VS Repl.it


I'm currently learning PHP so I'm doing some training, and I've come to a problem that I don't understand.

I wrote a few lines of code on Repl.it :

$msg = "Once upon a time...";

for ($i=0; $i < strlen($msg); $i++) {
  echo '<span>'.$msg[$i].'</span>';
  usleep(100000);
}

Here the code is running as intended (at least as I wanted it to), which is, one character is displayed after the other with a few milliseconds of delay between each. Like in RPG dialog boxes, for instance.

Now I imported my code to Visual Studio and ran it with Xampp on localhost, and everything is displayed only after the whole loop is done working. So, in this case, with "Once upon a time...", which is 19 character long, it loads for 100.000 ms * 19, and then I have the whole message displayed at once.

Any hint for me? :)


Solution

  • PHP runs on the server. By default, the server waits until the page is totally generated before sending the result to the client.

    You can use a combination of ob_flush() (flush the PHP output buffer) and flush() (flush the system output buffer) to achieve what you want :

    $msg = "Once upon a time...";
    
    for ($i=0; $i < strlen($msg); $i++) {
      echo '<span>'.$msg[$i].'</span>';
      usleep(100000);
    
      ob_flush();
      flush();
    }
    

    However, I think it would be better to be as quick as possible on the server side, and let javascript handles the fancy rendering on the client side.