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)