how to call a function in PHP after 10 seconds of the page load (Not using HTML)

后端 未结 12 967
终归单人心
终归单人心 2020-12-11 02:44

Is there any way to call a function 10 seconds after the page load in PHP. (Not using HTML.)

12条回答
  •  情话喂你
    2020-12-11 03:20

    If I interpret your question as "My page takes a long time to generate, now can I call a PHP function every 10 seconds while it generates" then there are several ways you can approach this...

    Time your loop, do something after 10 seconds of work...

    $nexttick=time()+10;
    $active=true;
    
    while ($active)
    {
        if (time()>=$nexttick)
        {
            my_tick_function();
            $nexttick=time()+10;
        }
    
        //now do some useful processing
        $active=do_some_work();
    }
    

    It's possible to use a technique like this to implement a progress meter for long running operations, by having your "tick" function output some javascript to update the HTML representing a progress meter.

    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.

    Using ticks...

    You can use the declare construct along with register_tick_function to have the PHP engine call your function every x 'ticks'. From the manual:

    A tick is an event that occurs for every N low-level tickable statements executed by the parser within the declare block. The value for N is specified using ticks=N within the declare blocks's directive section.

提交回复
热议问题