0

I'm having some issue in creating a script. So basically I do need to create a code that executes a function, waits x seconds and executes a second.

P.S: the 2 functions show a text via echo.

So what I did is that I did use sleep between the 2 functions. The problem is that when I do load the page, the loading bar of the browser keeps loading till the sleep(x) is finished, which I don't want to because it prevents the other content of the page (html, css) to load.

My code looks like this

execute_function1();
sleep(10);
execute_function2();

So I was wondering if there's any other way to create something like this, without using sleep. So all the content I do have on the site (html, css) can load even if there's some waiting between the 2 PHP functions.

Thank you in advance!

Stay safe!

Asez
  • 159
  • 1
  • 3
  • 13
  • That's very tricky to accomplish because every layer the output goes through (PHP, web server, proxy...) will try to buffer output. You can find some ideas at [this question](https://stackoverflow.com/questions/3133209/how-to-flush-output-after-each-echo-call). – Álvaro González May 09 '20 at 13:14
  • Use Javacsript instead. You are not able to achieve it in PHP – Jsowa May 09 '20 at 13:31

2 Answers2

0

Solution here !!!

execute_function1(); 
$now = time();
while ($now + 120 > time()) { // Set your own Sleep time 
execute_function2();
 }
Uday
  • 464
  • 3
  • 11
  • 1
    In which case does this one help? I guess it does nothing better than the original code - it even makes it worse, but maybe I am not deep enough in this php stuff - as far as I can see, this one still blocks loading the page and it executes execute_function2() more than once. – gth44 May 09 '20 at 15:00
0

You can send your Content to the Customers PC - check https://www.php.net/manual/de/function.ob-flush.php It will improve your websites Behaviour, but it won't make it feel "clean", "fluffy" and fun to use. Maybe this one can help you to achieve what you want - but I won't do it.

As (some people) already commented: I would not suggest to do that. PHP is still (in this case) a completely blocking technical solution - Your Browser will keep "spinning the wheel" until the PHP script ended. You can only conceal the way it works, but you will not be able to build a fully async-website that you want. Use other technology (Javascript with AJAX and stuff like that).

gth44
  • 77
  • 5