Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: sleep() for particular line of code

Tags:

php

sleep

is it possible to use sleep() (or some other function) to wait before execution?

I have for example:

<div>bla bla</div>
<?php
$a
echo $a; ?>

some divs and html
<?php
$b
echo $b; ?>

How to execute the first php script say 5 sec after the page has loaded but to show everything else as the page loads? If I use sleep() before the first php it will delay the whole page from loading.

like image 458
Gorna-Bania Avatar asked Oct 13 '16 10:10

Gorna-Bania


People also ask

How do I make PHP sleep?

In order to delay program execution for a fraction of a second, use usleep() as the sleep() function expects an int. For example, sleep(0.25) will pause program execution for 0 seconds.

How do I pause a PHP script?

The sleep() function in PHP is an inbuilt function which is used to delay the execution of the current script for a specified number of seconds. The sleep( ) function accepts seconds as a parameter and returns TRUE on success or FALSE on failure.

How do you call a PHP function after some time?

Using pcntl_alarm... Alternatively, if you have the Process Control support enabled in your build of PHP, you might be able to use pcntl_alarm to call a signal handler after a certain amount of time has elapsed.

How does sleep work in PHP?

The sleep() function delays execution of the current script for a specified number of seconds. Note: This function throws an error if the specified number of seconds is negative.


1 Answers

Yes, you can use sleep() to delay execution, but since the output is usually buffered and isn't sent to the browser until the script has finished the result isn't what you're after.

If you do a flush() and ob_flush() right after calling sleep() the output buffer is flushed and sent to the browser.

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

like image 85
Janek Avatar answered Sep 20 '22 17:09

Janek