在perl中实现js setTimeout功能

achieve js setTimeout functionality in perl

如何在 Perl 中实现 Javascript setTimeout 功能?这是我尝试用 Perl 编写的 javascript 代码片段。这可能使用线程吗?

alert("Event 1 occured");
setTimeout(function(){ alert("3 seconds elapsed"); }, 3000);
alert("Event 2 occured");

输出为:

 Event 1 occured
 Event 2 occured
 3 seconds elapsed

我有 perl 5.18.2 并且我在 Mac OSX

不需要线程,它们是 not great anyway in Perl. You can use an event loop just like JavaScript does, there's just not any in the Perl core. Two popular and well supported event loop ecosystems are IO::Async and Mojo::IOLoop(Mojolicious 网络框架背后的事件循环)。主要区别在于,与 JavaScript 不同,事件循环不是 运行 直到有东西启动它。

use strict;
use warnings;
use IO::Async::Loop;
print "Event 1 occurred\n";
my $future = IO::Async::Loop->new->delay_future(after => 3)->on_done(sub { print "3 seconds elapsed\n" });
print "Event 2 occurred\n";
$future->await; # run event loop until Future has been resolved

use strict;
use warnings;
use Mojo::IOLoop;
print "Event 1 occurred\n";
Mojo::IOLoop->timer(3 => sub { print "3 seconds elapsed\n" });
print "Event 2 occurred\n";
Mojo::IOLoop->start; # run event loop until no more events to wait for

查看 Mojolicious cookbook 以获得事件循环和非阻塞代码的高度概述。

参见alarm function. Otherwise, consider looking at threads.pm or , if you want to get feature parity with Javascript, one of the event loops, like AnyEvent or Mojo::IOLoop or IO::Async

对于线程,您的示例将是:

use strict;
use threads;
print("Event 1 occured\n");
async {
    sleep 3;
    print "3 seconds elapsed\n";
};
print("Event 2 occured\n");
$_->join for threads->list; # to wait until all threads have finished