PHP output text before sleep

前端 未结 6 1920
走了就别回头了
走了就别回头了 2020-12-02 00:36

I want PHP to output some text, then sleep for a second and a half, and then output some more text.



        
相关标签:
6条回答
  • 2020-12-02 00:41

    While Pentium10's solution will probably work, you might want to consider moving this to the client side. Have an async call to get the first value, print it, sleep for the required amount of time and then repeat for the second value.

    0 讨论(0)
  • 2020-12-02 00:43

    check this out

    <?php
    
    ob_start();
    
    echo 'Output one.';
    ob_flush();
    usleep(1500000);
    echo 'Output two.';
    ob_flush();
    
    ?>
    
    0 讨论(0)
  • 2020-12-02 00:49
    echo 'Output one.';
    ob_flush(); 
    flush();
    usleep(1500000);
    echo 'Output two.';
    
    0 讨论(0)
  • 2020-12-02 00:49

    Your problem is that this is PHP. It's a pre-processor. So the php script runs, outputs the first log, then sleeps, then outputs the second log, and only thén it's sent to and shown in your browser.

    You need javascript if you want the delay to be visible on your browser screen.

    function showLog () {
      $(".secondlog").show();
    }
    
    $(document).ready(function() {
      setTimeout(showLog,3000);
    });
    .firstlog {
      border: 1px solid #AEAEAE;
    }
    
    .secondlog {
      display: none;
      border: 1px solid #AEAEAE;
      margin-top: 20px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="firstlog">
      Output of first log
    </div>
    <div class="secondlog">
      Output of second log
    </div>
    
    <p>Wait for 3 seconds...</p>

    0 讨论(0)
  • 2020-12-02 00:52

    Pentium10's answer did not quite work for me.. However when I went to the PHP documentation page, there were a lot of good comments on there.

    http://php.net/manual/en/function.ob-flush.php

    This worked for me using Firefox 3.5.9, PHP 5.2.11, Apache running off local Windows 7 laptop:

    echo "test";
    ob_end_flush();
    flush();
    usleep(x);
    echo "test";
    

    The ob_end_flush() was crucial to getting data sent.

    0 讨论(0)
  • 2020-12-02 01:05

    I think it is more a http request/response issue. On the command line your script works fine.

    Normally the response is prepared completely and send to the client. If your response has such a size that multiple tcp packages have to be send, it could happen that the first packages are send, before you script is ready with processing. So it depends on the size of the output. Depending on the client/web browser, it could also happen that the first packages get rendered, before the complete response arrives at the client.

    As Noufal Ibrahim answered while im typing, I totally agree with him. Do it in a asynchrone manner.

    0 讨论(0)
提交回复
热议问题