July 15, 2013

Sleep() Function not doing what I think it should

HondaKillrsx’s Question:

First, correct me if i’m wrong but i’m under the assumption that when you run the Sleep() function, it pauses running the script where it is located in the script, not at the beginning. If that is true can someone tell me why the below script waits 5 seconds and then shows both echos at the same time. NOT echo the first statement on page load and then wait 5 seconds and then fire the second echo….

      echo "Your account username has been updated, you will now be redirected to the home page!";
      sleep(5);
      echo "REDIRECT!";

In your code PHP execution will pause for 5 seconds but it will not render itself part by part. i.e. It will not show the first statement and then the second. PHP keeps all its value in output buffer and display them when its finishes execution.

What happens is, it holds the value of first echo in output buffer and then waits for 5 seconds, then is holds another echo output in output buffer and shows all at once.

What you are trying to do is a lot easier in JS.

echo "Your account username has been updated, you will now be redirected to the home page!";
echo "<script> document.setTimeout(function() { document.location('redirect.html'); }, 5000); </script>";

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!