简体   繁体   English

javascript中的非阻塞setTimeout vs ruby​​中的sleep

[英]non-blocking setTimeout in javascript vs sleep in ruby

So, in javascript since it's event-driven by its nature it seems that setTimeout doesn't block. 因此,在javascript中,因为它的性质是事件驱动的,所以似乎setTimeout不会阻塞。 This means that if I do this: 这意味着如果我这样做:

setTimeout(function(){
  console.log('sleeping');
}, 10);
console.log('prints first!!');

It will output 'prints first!!' 它将输出'prints first!!' and then 'sleeping' . 然后'sleeping'

The js interpreter won't wait until setTimeout is done instead it executes the piece of code below it right away. js解释器不会等到setTimeout完成,而是立即执行它下面的代码片段。 When 10ms passes, then it executes the callback function. 当10ms通过时,它执行回调函数。

Now I have been playing around with ruby recently. 现在我最近一直在玩ruby。 I know that it has non-blocking support in event-machine library. 我知道它在事件机器库中具有非阻塞支持。 But I wonder if we can achieve something similar to setTimeout example I have just written in javascript with sleep or any function in ruby natively without event-machine support? 但是我想知道我们是否可以实现类似于setTimeout的例子我刚刚用javascript写入sleep或ruby中的任何函数而没有事件机器支持? Is this possible at all using closure proc or block or anything? 这是否可能使用闭包过程或块或任何东西? Thanks. 谢谢。

The setTimeout function is nothing at all like sleep since the former is asynchronous and the latter is synchronous. setTimeout函数完全没有sleep因为前者是异步的而后者是同步的。

The Ruby sleep method, like its POSIX counterpart, halts execution of the script. Ruby sleep方法与POSIX对应方法一样,会停止执行脚本。 The setTimer function in JavaScript triggers a callback at a future time. JavaScript中的setTimer函数会在将来触发回调。

If you want to trigger an asynchronous callback, you might need something like EventMachine to run an event loop for you. 如果要触发异步回调,可能需要像EventMachine这样的东西来为您运行事件循环。

You could get some very basic asynchronous behavior with threads: 您可以通过线程获得一些非常基本的异步行为:

timeout = Thread.new(Time.now + 3) do |end_time|
  while Time.now < end_time
    Thread.pass
  end
  puts "Ding!"
end

main = Thread.new do
  puts "Main"
end

main.join
timeout.join

I don't know if you want to go down the road of thread programming. 我不知道你是否想要进行线程编程。 That seems like overkill to me, but it's an option if you can't use EventMachine. 这对我来说似乎有些过分,但如果你不能使用EventMachine,这是一个选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM