Enis.b
Enis.b

Reputation: 23

Sleep function between loops runs before any loop executes

I'm trying to make the script wait 3 seconds before continuing to executing. The problem is the sleep function gets ran first and sleeps for 3 seconds, and after that both the loops gets ran.

if ($resultCheck > 0) {
  while ($row = mysqli_fetch_all($result)) {


      for ($i=0; $i < 3; $i++) {
        echo $row[$i][0];
      }
         sleep(3);

      $values = sizeof($row);
      for ($i=3; $i < $values; $i++) {
        echo $row[$i][0];
      }

    }


    }

Upvotes: 0

Views: 114

Answers (2)

Nadir Latif
Nadir Latif

Reputation: 3763

After each echo add this line: flush();. It will cause the output to be shown immediately.

Your code is correct, but the output is being shown after script ends. To show the output immediately, the output buffer needs to be flushed using flush() function.

Replace the line:

echo $row[$i][0];

with

echo $row[$i][0];
flush();

There may be further layers of output buffering which are causing the delay in output. See How to disable output buffering in PHP. In case flush does not work, you can use ob_flush along with flush.

Upvotes: 1

Ismael Padilla
Ismael Padilla

Reputation: 5566

Your code is running, but in order for your output to show you should be flushing the output buffer like such:

if ($resultCheck > 0) {
  while ($row = mysqli_fetch_all($result)) {
    for ($i=0; $i < 3; $i++) {
      echo $row[$i][0];
      ob_flush();
      flush();
    }
    sleep(3);

    $values = sizeof($row);
    for ($i=3; $i < $values; $i++) {
      echo $row[$i][0];
    }
  }
}

Your text may still not be flushing if it isn't past a certain length. If the above code does not work, we can use str_pad($text,4096); to lengthen the text to 4kb:

if ($resultCheck > 0) {
  while ($row = mysqli_fetch_all($result)) {
    for ($i=0; $i < 3; $i++) {
      echo str_pad( $row[$i][0], 4096);
      ob_flush();
      flush();
    }
    sleep(3);

    $values = sizeof($row);
    for ($i=3; $i < $values; $i++) {
      echo $row[$i][0];
    }
  }
}

Upvotes: 1

Related Questions