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.
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.
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.
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 .
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With