0

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];
      }

    }


    }
Enis.b
  • 23
  • 4
  • _“The problem is the sleep function gets ran first and sleeps for 3 seconds, and after that both the loops gets ran.”_ - and how exactly did you determine this was the case …? – 04FS Jul 03 '19 at 06:50
  • When the script gets ran it sleeps for 3 seconds before echoing the results. Both executes at the same time @04FS – Enis.b Jul 03 '19 at 18:45

2 Answers2

1

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.

Nadir Latif
  • 3,690
  • 1
  • 15
  • 24
  • It doesnt work. The sleep function still gets ran first and after that both loops gets executed at the same time – Enis.b Jul 03 '19 at 18:46
  • I have updated the answer. Call the function ob_flush() after flush(). So after each echo call flush, then ob_flush – Nadir Latif Jul 04 '19 at 09:35
1

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];
    }
  }
}
Ismael Padilla
  • 5,246
  • 4
  • 23
  • 35