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
setTimeoutfunction is nothing at all likesleepsince the former is asynchronous and the latter is synchronous.The Ruby
sleepmethod, like its POSIX counterpart, halts execution of the script. ThesetTimerfunction 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.