One interesting aspect of JavaScript is that, being event-driven in nature, the setTimeout function does not block. Consider the following example:
setTimeout(function(){
console.log('sleeping');
}, 10);
console.log('prints first!!');
This code will output 'prints first!!'
before 'sleeping'
, as the JavaScript interpreter immediately moves on to the code below the setTimeout call rather than waiting for it to finish. The callback function is then executed after a delay of 10ms.
I have recently started working with Ruby and discovered its non-blocking support in the event-machine library. This got me thinking - can we create a similar effect to the JavaScript setTimeout example using a native Ruby function like sleep
, without relying on event-machine? Is it possible to achieve such behavior using closures, procs, blocks, or any other feature of Ruby? I would appreciate any insights. Thank you!