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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With