36

The question sort of says it all - is there a function which does the same as the JavaScript function setTimeout() for PHP? I've searched php.net, and I can't seem to find any...

Latze
  • 1,843
  • 7
  • 22
  • 29
  • It is very late. But I answered your question. Now after php 5.5 you can achieve `setTimeOut()` very easily. Please check and accept it as an answer to the question. It may help others. – SkyRar Apr 22 '20 at 08:35

9 Answers9

18

There is no way to delay execution of part of the code of in the current script. It wouldn't make much sense, either, as the processing of a PHP script takes place entirely on server side and you would just delay the overall execution of the script. There is sleep() but that will simply halt the process for a certain time.

You can, of course, schedule a PHP script to run at a specific time using cron jobs and the like.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • It is a little hard to explain - what I wanted was exactly to pause the script :) Basically what I want to do is to "prank" one of my friends. I've made an input where you type in your name and when you submit a chatroom is simulated and to make it more realistic I want the messages from the stranger, my friend is "talking to", to appear one by one if you know what I mean :) – Latze Aug 08 '10 at 18:06
  • 11
    Timed events don't make sense because the script runs on server side? I'm not following the argument. Certainly they are less useful in PHP due to the absence of concurrency, but there's value in having a script that does something after a specific amount of time or on a certain instant. – Artefacto Aug 08 '10 at 18:08
  • 3
    @Latze that sounds like something you would want to do using JavaScript on client side, doesn't it? – Pekka Aug 08 '10 at 18:08
  • @Latze Then `sleep` or, for more fine-grained control `usleep`, is an adequate solution. – Artefacto Aug 08 '10 at 18:09
  • 1
    @Artefacto I see absolutely no use for *timed* events, because it's impossible to predict the script's flow and execution speed, so there is nothing to time against. *Event* events (like "after each mysql query" or "before outputting the first byte of data") might be useful if concurrency were possible, but *timing* makes sense only when there's human interaction as far as I can see. – Pekka Aug 08 '10 at 18:11
  • @Pekka Well, a timed event would be useful e.g. in a streaming Comet connection to send messages to the client on a specific time. The lack of concurrency could be worked around with in a [discrete event simulation](http://en.wikipedia.org/wiki/Discrete_event_simulation) manner, by keeping a list of future events and on each step of the loop extract the next event and pause the script until its time. And don't forget PHP is not used exclusively to serve webpages, this could be useful also for command line programs. – Artefacto Aug 08 '10 at 18:18
  • Just to add to @Artefacto argument... forcing PHP to delay a process it is very useful when testing a web application. For example, if you want to know how an Ajax request will behave waiting for lagged response from server. – raphie Jul 29 '16 at 14:14
  • @Pekka Hey now. JavaScript was once considered to be "only on server", and now it's a laughable comment. I can imagine a future where there is a viable way to use javascript to evaluate php so that php works on client side :) Heck I can write a basic translator myself, php and javascript are really really close, so much that they may as well be able to evaluate each other. Besides, standalone PHP benefits from timeouts for scheduling jobs rather than doing constant sleeps. – Dmytro Aug 14 '16 at 22:28
  • @Pekka oh man I remember when I used to do php, every timed event had to be done through cronjobs. Like resetting transaction limits, clearing a database table or sending data to another server and many more use cases. And some could say you can add a php file and include it on every page to check if the day has passed. But then you're using up resources just for the checks and you also need to check if it hasn't been updated already... If you are in the web development business there are many many use cases for timed events! – Ismail Dec 09 '17 at 01:18
  • Based on my previous comment I strongly suggest removing the comment about timed events not making sense. Also the reasoning. Just because something is server side it doesn't mean it doesn't need timed events. They sometimes need timed events more often than client user interfaces – Ismail Dec 09 '17 at 01:22
  • @Ismail the point is that the exact equivalent of what the OP wants to do - to delay execution of part of the code in the context of the current script - doesn't exist in PHP and wouldn't make any sense either. They clarified that's exactly what they want to do in the comments above. I'll add in a bit about cron jobs though. – Pekka Dec 09 '17 at 08:19
13

There's the sleep function, which pauses the script for a determined amount of time.

See also usleep, time_nanosleep and time_sleep_until.

Artefacto
  • 96,375
  • 17
  • 202
  • 225
  • it would still be nice to simulate this kind of code in php: http://hastebin.com/rujakezuco.lisp. sleep is blocking, timeouts are not. – Dmytro Aug 14 '16 at 22:35
13

PHP isn't event driven, so a setTimeout doesn't make much sense. You can certainly mimic it and in fact, someone has written a Timer class you could use. But I would be careful before you start programming in this way on the server side in PHP.

ars
  • 120,335
  • 23
  • 147
  • 134
  • 1
    But php has the tools to make your specific script be event driven. eg running php via console you may want to schedule multiple events at different times, at this point it makes perfect sense to have timeouts. – Dmytro Aug 14 '16 at 22:30
12

A few things I'd like to note about timers in PHP:

1) Timers in PHP make sense when used in long-running scripts (daemons and, maybe, in CLI scripts). So if you're not developing that kind of application, then you don't need timers.

2) Timers can be blocking and non-blocking. If you're using sleep(), then it's a blocking timer, because your script just freezes for a specified amount of time. For many tasks blocking timers are fine. For example, sending statistics every 10 seconds. It's ok to block the script:

while (true) {
    sendStat();
    sleep(10);
}

3) Non-blocking timers make sense only in event driven apps, like websocket-server. In such applications an event can occur at any time (e.g incoming connection), so you must not block your app with sleep() (obviously). For this purposes there are event-loop libraries, like reactphp/event-loop, which allows you to handle multiple streams in a non-blocking fashion and also has timer/ interval feature.

4) Non-blocking timeouts in PHP are possible. It can be implemented by means of stream_select() function with timeout parameter (see how it's implemented in reactphp/event-loop StreamSelectLoop::run()).

5) There are PHP extensions like libevent, libev, event which allow timers implementation (if you want to go hardcore)

pumbo
  • 3,646
  • 2
  • 25
  • 27
8

Not really, but you could try the tick count function.

Artefacto
  • 96,375
  • 17
  • 202
  • 225
Robin
  • 4,242
  • 1
  • 20
  • 20
4

http://php.net/manual/en/class.evtimer.php is probably what you are looking for, you can have a function called during set intervals, similar to setInterval in javascript. it is a pecl extension, if you have whm/cpanel you can easily install it through the pecl software/extension installer page.

i hadn't noticed this question is from 2010 and the evtimer class started to be coded in 2012-2013. so as an update to an old question, there is now a class that can do this similar to javascripts settimeout/setinterval.

Masu
  • 1,568
  • 4
  • 20
  • 41
3

Warning: You should note that while the sleep command can make a PHP process hang, or "sleep" for a given amount of time, you'd generally implement visual delays within the user interface.

Since PHP is a server side language, merely writing its execution output (generally in the form of HTML) to a web server response: using sleep in this fashion will generally just stall or delay the response.

With that being said, sleep does have practical purposes. Delaying execution can be used to implement back off schemes, such as when retrying a request after a failed connection. Generally speaking, if you need to use a setTimeout in PHP, you're probably doing something wrong.

Solution: If you still want to implement setTimeout in PHP, to answer your question explicitly: Consider that setTimeout possesses two parameters, one which represents the function to run, and the other which represents the amount of time (in milliseconds). The following code would actually meet the requirements in your question:

<?php
// Build the setTimeout function.
// This is the important part.
function setTimeout($fn, $timeout){
    // sleep for $timeout milliseconds.
    sleep(($timeout/1000));
    $fn();
}

// Some example function we want to run.
$someFunctionToExecute = function() {
    echo 'The function executed!';
}

// This will run the function after a 3 second sleep.
// We're using the functional property of first-class functions
// to pass the function that we wish to execute.
setTimeout($someFunctionToExecute, 3000);
?>

The output of the above code will be three seconds of delay, followed by the following output:

The function executed!

Joseph Orlando
  • 183
  • 3
  • 9
2

if you need to make an action after you execute some php code you can do it with an echo

 echo "Success.... <script>setTimeout(function(){alert('Hello')}, 3000);</script>";

so after a time in the client(browser) you can do something else, like a redirect to another php script for example or echo an alert

Geomorillo
  • 985
  • 1
  • 9
  • 14
2

There is a Generator class available in PHP version > 5.5 which provides a function called yield that helps you pause and continue to next function.

generator-example.php

    <?php
    function myGeneratorFunction()
    {
        echo "One","\n";
        yield;

        echo "Two","\n";
        yield;

        echo "Three","\n";
        yield;
    }

    // get our Generator object (remember, all generator function return
    // a generator object, and a generator function is any function that
    // uses the yield keyword)
    $iterator = myGeneratorFunction();

OUTPUT

One

If you want to execute the code after the first yield you add these line

    // get the current value of the iterator
    $value = $iterator->current();

    // get the next value of the iterator
    $value = $iterator->next();

    // and the value after that the next value of the iterator
    // $value = $iterator->next();

Now you will get output

One
Two

If you minutely see the setTimeout() creates an event loop.

In PHP there are many libraries out there E.g amphp is a popular one that provides event loop to execute code asynchronously.

Javascript snippet

setTimeout(function () {
    console.log('After timeout');
}, 1000);

console.log('Before timeout');

Converting above Javascript snippet to PHP using Amphp

Loop::run(function () {
    Loop::delay(1000, function () {
        echo date('H:i:s') . ' After timeout' . PHP_EOL;
    });
    echo date('H:i:s') . ' Before timeout' . PHP_EOL;
});

enter image description here

SkyRar
  • 1,107
  • 1
  • 20
  • 37