3

I'm trying to print something, wait 5 seconds and move to another page. I'm using the sleep function but for some reason nothing is printed and looks like it skips the print part.

It looks like this:

<?php
echo "Thank you!";
sleep(5);
?>
<script type="text/javascript"> window.location = '?a=home'; </script>
3
  • 2
    If you want to do that then you have to do it in JavaScript using setTimeout. PHP runs to completion before your page is displayed. Commented May 30, 2013 at 12:01
  • It's not skipping it, it's just sleeping before it renders to the client. The order of events you've written is "sleep 5 seconds, print something, move to another page." Commented May 30, 2013 at 12:01
  • possible duplicate of PHP issue with sleep() and redirect Commented May 30, 2013 at 12:03

5 Answers 5

11

You need to remove php and use only javascript:

<script type="text/javascript"> setTimeout(
function() {
    window.location = '?a=home';
}, 5000);
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sir! I will accept your answer as soon as the site lets me.
5

Perhaps it is better to use the HTML meta refresh tag. It has the same functionality but does so from the client:

<meta http-equiv="refresh" content="5;URL='?a=home'">

You can find more information here: http://www.metatags.info/meta_http_equiv_refresh

Comments

2

You can use javascript to do that :

setTimeout('window.location.replace("?a=home")',5000);

1 Comment

this answer will work, but it is bad practice to use a string for the code in setTimeout. Write it as a function, as per the top voted answer.
1

You can do it in javascript or using headers.

in js:

<script>
window.setTimeout('window.location = "?a=home"', 5000); //5000 = 5 secs

using headers:

header('Refresh: 5;url=page.php?a=home'); // 5 = 5 secs

related post: How to Redirect Page in PHP after a few seconds without meta http-equiv=REFRESH CONTENT=time

Comments

0

I'm pretty sure that using sleep just delays the program execution. You will only see the content when your PHP script is done and you are preventing it from doing so because of the sleep function.

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.