Build a countdown using a loop and sleep method in php - php

I am trying to make PHP print out a sequence numbers after a one second pause of execution using the sleep() method but then the code pauses execution for that duration and then executes the loop in a flash.
What i was expecting
I was expecting that for each iteration in that loop,it would print out a number and then call sleep() which would delay the code for a sec and then print out the next number and then delay and so on and so forth..
Code am using
<?php
$myarr=array(1,2,3,4,5,6,7,8,9,10);
foreach($myarr as $p){
//print out a number and then pause for a sec
echo "$p <br/>";
sleep(1);
/*the line above instead makes the thread sleep for one second and then prints the rest of the numbers in a flash instead of printing a single number and pausing and so on and so forth*/
}
?>

Basically PHP does do exactly what you want... just not on the browser...
A way to go is via ob_flush :
<?php
if (ob_get_level() == 0) ob_start();
for ($i = 0; $i<10; $i++){
echo "<br>" . $i;
echo str_pad('',4096)."\n";
ob_flush();
flush();
sleep(2);
}
echo "Done.";
ob_end_flush();
?>
This will print a number every 2 seconds... but it's eh... not the best at what it does.... at least the first 4-5 seconds - meaning 0,1 and maybe 2 are already printed when we start seeing the sleep do it's trick.

You may achieve it by flushing the output before the sleep
The code will be :
<?php
$myarr=array(1,2,3,4,5,6,7,8,9,10);
foreach($myarr as $p){
//print out a number and then pause for two seconds
ob_start();
echo "$p <br/>";
$size = ob_get_length();
ob_end_flush();
#ob_flush();
flush();
sleep(2);
}
?>

Related

How to print current index or for loop in PHP?

The below PHP code returns 12345678910...... at a stretch.
for ($i=0; $i<1000; $i++) {
sleep(1);
echo $i;
}
How can I get it to print only the current loop number instead of printing all numbers together?
This can be easily done in php cli using the backspace character "\x08"
<?php
$length = 0;
for ($i=0; $i<1000; $i++)
{
// delete as much character as the length of the previous number
echo str_repeat("\x08", $length);
sleep(1);
echo $i;
// get the length of the number, so you know how much you have to delete
$length = strlen((string)$i);
}
This is my suggested answer (applicable to browser)
a) I believe the OP wants to have the output generated to the browser interface
b) To generate the output of the count during the 1-second sleep, we need to flush the output before each sleep
c) In a browser interface, it is not possible to generate a backspace, so let's do a javascript trick to update the div
<div id=output1></div>
<?php
$index=0;
while($index < 1000) {
ob_start();
echo "<script>document.getElementById('output1').innerHTML=" . $index . "</script>";
ob_end_flush();
#ob_flush();
flush();
sleep(1);
$index++;
}
?>

While loop output one digit per loop at the same position

echo "counter: ";
$i=1;
while ($i <= 5) {
print($i);
sleep(1);
$i++;
}
The above will output: counter: 12345 I need to output eg.: loop 3 - counter: 3 (one digit per loop)
How to do it:
1) When running in a browser?
2) When running from command line (php index.php)?
I think you want to make an auto-updated string. It's impossible to make it with only PHP. You should use Javascript (or a library like jQuery) and send the data from PHP via Ajax call.
You can even do this only with Javascript.
var counter = 1;
setInterval(function () {
counter++;
}, 5);
For command line you can use your code with "\r" at the end of the string.
$i=0;
while ($i <= 5) {
sleep(1);
$i++;
echo "counter: $i\r";
}
I think this is what you need. The counter string was brought inside the loop and a break was added for a new line simulation. Also the < was changed to <= as the loop was running for 4 times instead of 1.
$i=1;
while ($i <= 5) {
print("counter: $i <br>");
sleep(1);
$i++;
}

PHP Infinite Loop Not Terminated after 60 seconds

I created an infinite PHP while loop which incremented a variable then echoed:
$num = 1;
while($num >0) {
echo $num . "<br/>";
$num++;
}
I was expecting this to be killed/terminated after 60 seconds as the setting in php.ini are as follows:
max_execution_time 60 60
max_input_time 60
Sorry if I'm wrong but I expected to see the job killed in the browser (no new echos!)...
Can anyone give me more information on infinite PHP jobs running and when they are actually killed on the server?
You are confusing execution time with wall clock time. They are not the same thing. The processor is using very little execution time on each loop of your code. It will eventually time you out but it's going to take a lot longer than a minute.
Think of it this way, your processor may be running at 2GHz. How many instructions do you think it takes to do one of your loops? The time on echo is big (i.e. slow) and it doesn't count toward processor execution time.
//using set_time_limit
// starting php code here
echo "starting...\n";
// set_time_limit(10); //either would work
ini_set("max_execution_time", 10); //either would work
function doSomeExpensiveWork($currentTime){
for ($r = 0; $r < 100000; $r++){
$x = tan(M_LNPI+log(ceil( date("s")*M_PI*M_LNPI+100)));
}
}
try{
while(true)
{
$currentTime = date("H:m:s");
echo $currentTime, "\n";
doSomeExpensiveWork($currentTime);
}
} catch (Exception $e) {
//echo 'Caught exception: ', $e->getMessage(), "\n";
}
echo "this will not be executed! $x";
// code end

php echo the result while iterating through the loop

I am execution loop and inside loop there is data processing function inside loop.
for($i = 0 ; $i <=680 ; $i = $i + 40)
{
$url = 'http://www.yelp.com/biz/franchino-san-francisco?start=80';
$root = yelp($url);
var_dump($root);
}
This loop takes long time to execute, and results are echoed at the end when entire loop completes.
How can I echo the result during each iteration?
Actually what happens here? does to result are stored in buffer and at the end echoed or what?
PHP buffers the output.
If you want to output stuff to the browser immediately you can use the flush() and ob_flush() functions:
for ($i = 0; $i <= 680; $i += 40) {
$url = 'http://www.yelp.com/biz/franchino-san-francisco?start=80';
$root = yelp($url);
var_dump($root);
flush();
ob_flush();
}
If you are executing PHP through a web-page, this would be the behaviour.
PHP is a server side language and all code will be executed before displaying the output to the client. (using a browser)
If you want to display the result within the loop, better use console / cmd (command line)
Here is something that will help you use PHP with commandline.

Variable empty, while after calculation shouldnt be empty. How to do this correctly?

imagine I want to calculate speed of loading,
and then echo that calculated value.
However... I wish to echo that value not at the end of the page, on the bottom of html, but somewhere in the middle of the html:
$s = microtime(true);
<html><head>...</head><body>
echo $laadtijd . " seconds"; //echo value, after calculation completed
</body></html>
$e = microtime(true);
$laadtijd = round($e - $s, 3); //fill in the value
However, now the page shows an empty value for $laadtijd, while it has been calculated! How to solve this?
You can do that by doing:
<?php
// Start time
$s = microtime(true);
// Holds the output buffer
ob_start();
echo '
<html>
<head>...</head>
<body>....
TIME_CALCULATED seconds.
</body>
</html>'; // TIME_CALCULATED will be our flag
// Get the output
$output = ob_get_contents();
ob_end_clean();
// End time
$e = microtime(true);
$laadtijd = round($e - $s, 3);
// Echo the output
echo str_replace('TIME_CALCULATED', $laadtijd, $output);
?>
This simply holds the output buffer with all the content and replaces our flag TIME_CALCULATED in the buffer with the time.
For more info read Output Control Functions on PHP's Manual.
HOW CAN YOU CALCULATE LOAD SPEED OF ENTIRE PAGE UNLESS IT HAS BEEN LOADED? YOU calculated $laadtijd somewhere towards the end then how can you echo it in middle???
using microtime its impossible to be precise with time taken to load page.(i am not sure though)
<?php
$s = microtime(true);
?>
<html><head>...</head>
<body>
show you entire page
<?php
$e = microtime(true);
$laadtijd = round($e - $s, 3);//calculate first then echo
echo $laadtijd . " seconds";
?>
</body></html>

Categories