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>
Imri Persiado
  • 1,857
  • 8
  • 29
  • 45
  • 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. – Jon May 30 '13 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." – David May 30 '13 at 12:01
  • possible duplicate of [PHP issue with sleep() and redirect](http://stackoverflow.com/questions/12298909/php-issue-with-sleep-and-redirect) – Jon May 30 '13 at 12:03

5 Answers5

11

You need to remove php and use only javascript:

<script type="text/javascript"> setTimeout(
function() {
    window.location = '?a=home';
}, 5000);
</script>
Vlad Bereschenko
  • 338
  • 1
  • 3
  • 11
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

Erik Schierboom
  • 16,301
  • 10
  • 64
  • 81
2

You can use javascript to do that :

setTimeout('window.location.replace("?a=home")',5000);
Bouffe
  • 770
  • 13
  • 37
  • 1
    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. – Spudley May 30 '13 at 12:11
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

Community
  • 1
  • 1
skparwal
  • 1,086
  • 6
  • 15
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.

Ronnie Jespersen
  • 950
  • 2
  • 9
  • 22