Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add delay before PHP echo

Tags:

php

I have an echo call within a simple PHP script to print a parameter on screen:

<body>
<p>the string will appear in 30 seconds:</p>
<p><?php echo $string; ?></p>
</body>

I want that before the "echo" runs, that system will wait X seconds. hence, the text "the string will appear after 30 seconds" will appear first, and after 30 seconds, the $string will appear below it. How it can be done? the Sleep() tends to delay the whole page before loading.

like image 301
AssafT Avatar asked Mar 07 '14 12:03

AssafT


People also ask

How do you delay a function in PHP?

The sleep() function in PHP is an inbuilt function which is used to delay the execution of the current script for a specified number of seconds. The sleep( ) function accepts seconds as a parameter and returns TRUE on success or FALSE on failure.

Is there a wait function in PHP?

Description ¶ The wait function suspends execution of the current process until a child has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function.

Why echo is faster than print in PHP?

They are both used to output data to the screen. The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print .

Does PHP wait for function to finish?

PHP is single-threaded, which means that it executes one instruction at a time before moving on. In other words, PHP naturally waits for a function to finish executing before it continues with the next statement.


Video Answer


1 Answers

You could use PHP sleep to wait 30 seconds:

<body>
<p>the string will appear in 30 seconds:</p>
<p><?php sleep(30); echo $string; ?></p>
</body>

However, when you do this, depending on your PHP and Apache settings, your entire page may wait 30 seconds before fully rendering and sending an HTTP response back to the client.

Additionally, if you send a partial response to the client, it may sometimes wait to render content until enough of the page is loaded to present the data (e.g. in the case of a table).

Try using JS instead, to allow the page to render and then present the hidden data after 30 seconds:

<body>
<p>the string will appear in 30 seconds:</p>
<p id="sleep" style="display:none"><?php echo $string; ?></p>
<script>
    window.setTimeout(function() {
        document.getElementById('sleep').style.display = '';
    }, 30000);
</script>
</body>
like image 105
Steven Moseley Avatar answered Sep 23 '22 13:09

Steven Moseley