Is there any way to call a function 10 seconds after the page load in PHP. (Not using HTML.)
if you mean after the page has loaded you will need to use javascript/ajax/jquery to do so.
You can create a Javascript timer that calls the function every ten seconds.
Tutorial here
(10 seconds is 10000 milliseconds)
If you really must do it within the same PHP script, the cleanest way would be a fork.
Or if that's not possible, here's a really bad hackish way of doing it:
<?php
ignore_user_abort(1);
page_output_stuff();
// ...
flush();
sleep(10);
do_something_after_script();
?>
If you're doing this to output stuff to the user after a delay, the above can be made to work but it's a really ugly way of doing it. Just use AJAX instead.
This code works. Edited from randell's answer.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
setTimeout(function() { $('#some_id').load('index.php'); }, 10000);
});
</script>
Thanks to randell
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...
$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.
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.
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.
PHP is a server side scripting language. If you need to check if something has loaded already in the client side, you will need a client-side scripting language like JavaScript.
You might need to use jQuery for your purpose to simplify things.
jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.
First, download jQuery. In the head tag of your HTML, add this:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
// Check if the page has loaded completely
$(document).ready( function() {
setTimeout( function() {
$('#some_id').load('index.php');
}, 10000);
});
</script>
In the body of your HTML, add this:
<div id="some_id"></div>