PHP 是否有类似于 setTimeout() (JavaScript) 的函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3435418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:35:48  来源:igfitidea点击:

Is there a function similar to setTimeout() (JavaScript) for PHP?

phpjavascriptsettimeout

提问by Latze

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

这个问题有点说,这一切-有哪个不一样的功能的JavaScript函数的setTimeout()PHP?我搜索了php.net,但似乎找不到任何...

采纳答案by Pekka

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.

无法延迟当前脚本中部分代码的执行。这也没有多大意义,因为 PHP 脚本的处理完全在服务器端进行,您只会延迟脚本的整体执行。有,sleep()但这只会在一段时间内停止该过程。

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

当然,您可以使用 cron 作业等安排 PHP 脚本在特定时间运行。

回答by ars

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 classyou could use. But I would be careful before you start programming in this way on the server side in PHP.

PHP 不是事件驱动的,因此 setTimeout 没有多大意义。你当然可以模仿它,事实上,有人写了一个你可以使用的Timer 类。但是在您开始在 PHP 的服务器端以这种方式进行编程之前,我会小心。

回答by Artefacto

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

有一个sleep函数,它可以将脚本暂停一段确定的时间。

See also usleep, time_nanosleepand time_sleep_until.

另见usleep,time_nanosleeptime_sleep_until

回答by AlexM

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

关于 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.

1) PHP 中的计时器在长时间运行的脚本(守护进程,也可能是 CLI 脚本)中使用时有意义。因此,如果您不开发那种应用程序,那么您就不需要 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:

2) 定时器可以是阻塞的和非阻塞的。如果您使用的是sleep(),则它是一个阻塞计时器,因为您的脚本只会冻结指定的时间。对于许多任务,阻塞计时器很好。例如,每 10 秒发送一次统计信息。阻止脚本就可以了:

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.

3) 非阻塞定时器只在事件驱动的应用程序中有意义,比如 websocket-server。在此类应用程序中,事件可能随时发生(例如传入连接),因此您不能sleep()(显然)阻止您的应用程序。为此,有事件循环库,如reactphp/event-loop,它允许您以非阻塞方式处理多个流,并且还具有计时器/间隔功能。

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()).

4) PHP 中的非阻塞超时是可能的。它可以通过stream_select()带有超时参数的函数来实现(查看它是如何在reactphp/event-loop StreamSelectLoop::run() 中实现的)。

5) There are PHP extensionslike libevent, libev, eventwhich allow timers implementation (if you want to go hardcore)

5) 有libevent, 之类的 PHP 扩展libevevent它允许定时器实现(如果你想成为硬核)

回答by Robin

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

不是真的,但你可以试试滴答计数功能

回答by Joseph Orlando

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

警告:您应该注意,虽然该sleep命令可以使 PHP 进程挂起或在给定的时间内“休眠”,但您通常会在用户界面中实现视觉延迟。

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.

由于 PHP 是一种服务器端语言,只需将其执行输出(通常以 HTML 的形式)写入 Web 服务器响应:以这种方式使用睡眠通常只会停止或延迟响应。

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.

话虽如此,睡眠确实有实际用途。延迟执行可用于实现回退方案,例如在连接失败后重试请求时。一般来说,如果你需要在 PHP 中使用 setTimeout,你可能做错了什么。

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中实现setTimeout,明确回答你的问题:考虑setTimeout有两个参数,一个代表要运行的函数,另一个代表时间量(以毫秒为单位)。以下代码实际上可以满足您问题中的要求:

<?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!

函数执行了!

回答by Masu

http://php.net/manual/en/class.evtimer.phpis 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.

http://php.net/manual/en/class.evtimer.php可能就是你要找的,你可以在设定的时间间隔内调用一个函数,类似于 javascript 中的 setInterval。它是 pecl 扩展,如果您有 whm/cpanel,您可以通过 pecl 软件/扩展安装程序页面轻松安装它。

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.

我没有注意到这个问题是从 2010 年开始的,而 evtimer 类是在 2012-2013 年开始编写的。因此,作为对旧问题的更新,现在有一个类可以执行类似于 javascripts settimeout/setinterval 的操作。

回答by Geomorillo

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

如果您需要在执行一些 php 代码后执行操作,您可以使用 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

因此,在客户端(浏览器)一段时间后,您可以执行其他操作,例如重定向到另一个 php 脚本或回显警报

回答by SkyRar

There is a Generatorclass available in PHP version > 5.5 which provides a function called yieldthat helps you pause and continue to next function.

GeneratorPHP 版本> 5.5 中有一个可用的类,它提供了一个名为的函数yield,可帮助您暂停并继续执行下一个函数。

generator-example.php

生成器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 yieldyou add these line

如果你想在第一个之后执行代码,yield你添加这些行

    // 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.

如果您仔细地看到 setTimeout() 会创建一个事件循环。

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

在 PHP 中有许多库,例如amphp是一种流行的库,它提供事件循环来异步执行代码。

Javascript snippet

Javascript 片段

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

console.log('Before timeout');

Converting above Javascript snippet to PHP using Amphp

使用 Amphp 将上面的 Javascript 片段转换为 PHP

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

在此处输入图片说明