在perl中实现js setTimeout功能

时间:2018-10-01 22:03:52

标签: multithreading perl settimeout

如何在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上

2 个答案:

答案 0 :(得分:2)

不需要线程,它们是not great anyway in Perl。您可以像JavaScript一样使用事件循环,Perl核心中没有任何事件循环。 IO::AsyncMojo::IOLoop(Mojolicious Web框架背后的事件循环)是两个流行且得到良好支持的事件循环生态系统。主要区别在于,与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,以获取有关事件循环和非阻塞代码的高级概述。

答案 1 :(得分:0)

请参见alarm功能。否则,请考虑查看threads.pm或,如果要使用Javascript获得功能奇偶校验,则事件循环之一,例如AnyEventMojo::IOLoopIO::Async

使用threads,您的示例将是:

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