1

I'm trying to insert delays between echo commands and wanted to use the sleep() function. Unfortunately, as I understand the sleep() function in PHP delays the whole script. I was wondering if there's a trick around this?

I'm trying to accomplish the following

  1. echo a line
  2. sleep(2)
  3. echo next line
  4. sleep(2)

Is there a way to do this with PHP without any JS or something else?

7
  • Is the script run interactive from the CLI or being used to generate a web page? Commented Jun 6, 2013 at 23:54
  • 2
    Are you talking about delaying the appearance of different lines in the user's browser? Commented Jun 6, 2013 at 23:55
  • 2
    Sounds like you want to use JavaScript. Commented Jun 6, 2013 at 23:58
  • PHP works on server so PHP can put to (long, long) sleep only server not browser ;) Commented Jun 7, 2013 at 0:00
  • 1
    It's not clear what you mean by "delays between echo commands" or "delays the whole script". Can you give more context on what you're trying to do? Commented Jun 7, 2013 at 0:03

2 Answers 2

2

I think what you need is just some javascript:

<p id="p"></p>

<script>

setTimeout(function() {
  document.getElementById('p').innerHTML = "line1";
}, 2000);

setTimeout(function() {
  document.getElementById('p').innerHTML = "line2";
}, 4000);

</script>
Sign up to request clarification or add additional context in comments.

Comments

2

I'm assuming when you say you don't want to delay the whole script that you're really talking about the output... you don't want to delay the entire output, just the stuff after the sleep.

There's a couple things to keep in mind:

  1. IE tends to not display anything until it has received 1k of content. To counter this, you need to start your script by outputting some padding... 1024 spaces, for example. (which will have no effect on the actual HTML display)

  2. You need to make sure your content is not being compressed in any way by the web server

  3. You need to flush your output buffer after echoing.

That all adds up to something that looks like this:

<?php
    // turn off output compression
    @apache_setenv('no-gzip', 1);
    ini_set('zlib.output_compression', 0);

    // no need to flush after every output call
    ob_implicit_flush(true);

    // some padding for IE
    echo(str_repeat(" ", 1024) . "\n");

    echo("Something here<br />");
    sleep(5);

    echo("Something else<br />");
?>

1 Comment

jcsanyi the part about the output in your reply is exactly what I was thinking. But I think I'm better of letting the whole thing process and do the delays at the client side.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.