Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP output text before sleep

Tags:

text

php

sleep

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

<?php

echo 'Output one.';

usleep(1500000);

echo 'Output two.';

?>

My problem is that all text is being put out simultaneously - after having waited those 1.5 seconds. I have read something about a function called flush - but it doesn't seem to work. Maybe I'm not using it write. Any help would be appreciated ^^

Thanks in advance!

like image 395
arik Avatar asked Jun 20 '10 10:06

arik


People also ask

Is there a wait function in PHP?

The wait function suspends execution of the current process until a child has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function.

How do you delay a function 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.

How does PHP sleep work?

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 I put PHP to sleep?

Delays the program execution for the given number of seconds . Note: 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.


2 Answers

check this out

<?php

ob_start();

echo 'Output one.';
ob_flush();
usleep(1500000);
echo 'Output two.';
ob_flush();

?>
like image 196
Pentium10 Avatar answered Oct 13 '22 01:10

Pentium10


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.

like image 44
abelito Avatar answered Oct 13 '22 00:10

abelito