Comparing non-blocking setTimeout in JavaScript versus sleep in Ruby

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!

Answer №1

It's important to understand that the setTimeout function operates differently from the sleep function. While setTimeout is asynchronous, sleep is synchronous in nature.

In Ruby, the sleep method behaves similarly to its POSIX equivalent by pausing script execution. On the other hand, the setTimer function in JavaScript schedules a callback to be executed at a later time.

For triggering an asynchronous callback, tools like EventMachine may come in handy to manage an event loop efficiently.

Answer №2

If you're looking for a simple way to introduce asynchronous behavior, you could consider using threads:

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

main = Thread.new do
  puts "Main thread"
end

main.join
timeout.join

While threading may be seen as excessive by some, it's an alternative if EventMachine isn't suitable for your needs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with AJAX POST request: PHP failing to establish session

I would like to pass the element's id to PHP and create a session for it. This snippet is from a PHP file: <?php $sql = "SELECT id FROM products"; $result = mysqli_query($con,$sql); while($row = mysqli_fetch_array($result)) { ?> <tr cl ...

Ways to avoid scrolling on a fixed element

Here is the HTML setup I have... body .top .content The issue I am facing is that when scrolling reaches the end of the ul in the .top element, the background starts to scroll. This can be quite disorienting and makes the site slow on tablets. Even ...

using database URL as an AJAX parameter

I am currently working on a Python CherryPy controller that needs to validate a database URL by attempting a connection. However, I am facing challenges with passing the parameter to the method. Below is my AJAX call: $.ajax({ async: false, ty ...

Issue detected with XMLHttpRequest - "The requested resource does not have the 'Access-Control-Allow-Origin' header."

Currently, I am working on the frontend development of an application using Angular 2. My focus is on loading an image from a third-party site via XMLHttpRequest. The code I have implemented for this task is as follows: loadFile(fileUrl) { const ...

How can I save files to the ~/Documents directory using Node.js on my Mac computer?

Trying to work with the user's Documents folder in Node.js on macOS: var logger = fs.createWriteStream('~/Documents/somefolderwhichexists/'+title+'.txt'); Encountering an error without clear cause. Error message received: Unca ...

Unable to get ng-submit function to work properly within the Laravel PHP framework

Hello everyone, I have an inquiry regarding Laravel/AngularJS. In my project, there is a form where users can post questions. However, when I click the submit button, no requests are sent (as per inspection in Google Chrome). Interestingly, the Log in int ...

Angular - Ensure completion of a function call before continuing with the code execution

I'm currently working on developing a code snippet that checks for potential adverse drug reactions between two medications. Within my checkForClash() function, there is a call to getCollisionsList(), which is responsible for populating the interacti ...

Toggle display of divID using Javascript - Conceal when new heading is unveiled

At the moment, I have implemented a feature where clicking on a title reveals its corresponding information. If another title is clicked, it opens either above or below the previously opened title. And if a title is clicked again, it becomes hidden. But ...

Improving callback functions in Express/NodeJs for a more pleasant coding experience

function DatabaseConnect(req, res) {...} function CreateNewUser(req, res) {...} function ExecuteFunctions (app, req, res) { // If it's a POST request to this URL, run this function var firstFunction = app.post('/admin/svc/DB', func ...

Which is better for your website: SSG vs SSR?

Currently, I am diving into Nextjs and constructing a website using this framework. The site includes both public pages, protected routes (like user dashboard, user project details, and general user data), as well as product pages. I have been pondering h ...

Encountering a rollbackFailedOptional error during the NPM Install process

When attempting to use various command prompts like Windows Powershell, command prompt as an admin, and bash CMD, I encountered the same error message after trying to run npm install: npm install npm@latest -g The specific error message was: [...] / ro ...

Matching Tables with JavaScript and JSON

After hours of coding, I'm stuck on a simple task and could really use some assistance. The "users" object contains user account information, with the function "get" meant to retrieve matching objects from this array. var users = [ { name ...

Troubleshooting JavaScript directly on the client side

As a JavaScript beginner hoping to transform into a JavaScript expert, debugging is an essential skill I must master. Currently, I am utilizing Chrome debugger tools to tackle a complex array of spaghetti JavaScript code that resembles a cryptic puzzle wai ...

Find out if OpenAI's chat completion feature will trigger a function call or generate a message

In my NestJS application, I have integrated a chat feature that utilizes the openai createChatCompletion API to produce responses based on user input and send them back to the client in real-time. Now, with the introduction of function calls in the openai ...

npm installs a multitude of dependencies

Recently, I purchased an HTML template that includes various plugins stored in a directory named bower_components, along with a package.js file. While trying to add a new package that caught my interest, I opted to utilize npm for the task. Upon entering ...

Instructions on including a directory in the package.json file for publication on npm

I am facing an issue when attempting to publish a module in the npm repository as it is not recognizing the 'lib' folder. Even though I have included it in the package.json file as shown below, the 'lib' folder contents are not being re ...

Having difficulties with JavaScript's if statements

I'm facing an issue with my JavaScript code that is meant to modify the value of a price variable and then display the updated price. The problem arises when I have multiple select options, as the price only reflects the ID of the last statement. Here ...

What is the best way to delete comments from the config.js file?

I'm looking for a way to remove comments from my config.js file, which is acting as a JSON file in my project. The config file has both single line comments like this: //comment goes here and multi-line comments like this: /* comments goes here */ ...

Am I on the right track with incorporating responsiveness in my React development practices?

Seeking advice on creating a responsive page with React components. I am currently using window.matchMedia to match media queries and re-rendering every time the window size is set or changes. function reportWindowSize() { let isPhone = window.matchMed ...

Error 404 encountered while attempting to access dist/js/login in Node.JS bootstrap

I currently have a web application running on my local machine. Within an HTML file, I am referencing a script src as /node_modules/bootstrap/dist/js/bootstrap.js. I have configured a route in my Routes.js file to handle this request and serve the appropri ...