4

I have a php file test.php. I want to echo or print "Success" after 5 seconds, soon after the php file is called or loaded or opened by the browser. Incidentally, sometimes I may want to execute / initialise some functions after a specific interval of time.

How can I make a time-oriented task using php, like printing a message after 5 seconds?

5 Answers 5

6

You can interrupt the execution of your script using sleep(). If you want sub-second precision, you can use usleep():

# wait half a second (500ms)
usleep(500000);
echo 'Success';
Sign up to request clarification or add additional context in comments.

Comments

5

It is usually not a good idea to do this in PHP. The PHP script should run as quickly as possible. Delaying the PHP execution of the PHP script

  • is going to use more server resources than necessary
  • could meet timeout limits in PHP, on the server or in the browser.

The best alternative is JavaScript and its setTimeout():

setTimeout(function() { alert ("Done!"); }, 5000); 

(alternatively, instead of alert(), you could instruct JavaScript to show a dialog or similar.)

if you do not want to depend on JavaScript, you could consider a META redirect taking the user to a page containing the "Done!" message.

<meta http-equiv="refresh" content="5; url=http://example.com/">

Comments

0

You can use jQuery timer to delay execution of subsequent items in the queue

http://api.jquery.com/delay/

http://www.w3schools.com/js/js_timing.asp

<html>
<head>
<script type="text/javascript">
function timeMsg()
{
var t=setTimeout("alertMsg()",3000);
}
function alertMsg()
{
alert("Hello");
}
</script>
</head>

<body>
<form>
<input type="button" value="Display alert box in 3 seconds"
onclick="timeMsg()" />
</form>
</body>
</html>

Comments

0
while(1){
    sleep($time);
    youfunction();
}

Comments

0

If you have to, you can use this: http://php.net/manual/en/function.register-tick-function.php but watch out for impact on performance.

In the called function you check if enough time has passed, and if so unregister the tick function and then run the appropriate code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.