Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. This means that if I do this:

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

It will output 'prints first!!' and then 'sleeping'.

The js interpreter won't wait until setTimeout is done instead it executes the piece of code below it right away. When 10ms passes, then it executes the callback function.

Now I have been playing around with ruby recently. 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? Is this possible at all using closure proc or block or anything? Thanks.

like image 967
Benny Tjia Avatar asked Feb 16 '12 03:02

Benny Tjia


2 Answers

The setTimeout function is nothing at all like sleep since the former is asynchronous and the latter is synchronous.

The Ruby sleep method, like its POSIX counterpart, halts execution of the script. The setTimer function in JavaScript triggers a callback at a future time.

If you want to trigger an asynchronous callback, you might need something like EventMachine to run an event loop for you.

like image 61
tadman Avatar answered Nov 14 '22 23:11

tadman


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.

like image 26
Brandan Avatar answered Nov 14 '22 21:11

Brandan