Using PHP Sleep Like Javascript setTimeout: 2023 Code Examples

How to Use the Sleep() function in PHP PHP sleep() halts a running script for specific seconds. It is a synchronous and blocking timer that may surprise you if you switch from an async context. Let’s quickly go through some highlights and clarify some presumptions.. PHP Sleep Function Code Example <?php /* @params $fn - callback function $seconds - halt time in seconds (expects an integer greater than or equal to zero) */ function setTimeout($fn, $seconds){ sleep($seconds); $fn(); } $greet = function() { echo 'Hello' . "\n"; }; echo "Before calling setTimeout() ".date('h:i:s') . "\n"; setTimeout($greet, 5); echo "After timeout ".date('h:i:s') . "\n"; /* Before calling setTimeout() 07:44:18 Hello After timeout 07:44:23 */ ?> Article Highlights An asynchronous & non-blocking timer doesn’t block a thread but puts off the execution of a function for a defined timeout duration. PHP sleep() function is not an asynchronous function; therefore, it blocks the…

read more