Skip to content

Instantly share code, notes, and snippets.

@rodcul
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodcul/675dc6657610892bd246 to your computer and use it in GitHub Desktop.
Save rodcul/675dc6657610892bd246 to your computer and use it in GitHub Desktop.
RUBY (sync) vs JS (async)

Ruby Synchronous code:

def short
  puts 'short - ' + Time.now.to_s
end

def long
  sleep 2
  puts 'long - ' + Time.now.to_s
end

short
long
short

If we run this code we'll see that it runs LINEARLY, in a blocking fashion. We passed it short/long/short and it returned in that order. Look closely at the timestamps.

$ ruby sync.rb
short - 2015-06-09 23:25:36 +0100
long - 2015-06-09 23:25:38 +0100
short - 2015-06-09 23:25:38 +0100

Javascript Asyncronous code:

function short() {
	console.log("short - " + Date())
}

function long() {
	setTimeout(function() {
		console.log("long - " + Date())
	}, 2000)
}

short()
long()
short()

If we run the js in the terminal we'll see that even though we passed it short/long/short it returned the results as they became available (short/short/run). Compare the timestamps this time.

$ node sync.js
short - Tue Jun 09 2015 23:25:48 GMT+0100 (WEST)
short - Tue Jun 09 2015 23:25:48 GMT+0100 (WEST)
long - Tue Jun 09 2015 23:25:50 GMT+0100 (WEST)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment