Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created December 2, 2015 01:11
Show Gist options
  • Save JoshCheek/4e2108c0c441579de10e to your computer and use it in GitHub Desktop.
Save JoshCheek/4e2108c0c441579de10e to your computer and use it in GitHub Desktop.
Example of how JS async works for a student
class JavaScript
def initialize
@work = []
@background_worker_count = 0
end
def run(&code)
@work << code
while @work.any? || @background_worker_count > 0
instance_eval &@work.shift if @work.any?
end
end
def set_timeout(milliseconds, &callback)
@background_worker_count += 1
Thread.new do
sleep milliseconds/1000.0
@work << callback
@background_worker_count -= 1
end
end
end
JavaScript.new.run do
puts "first: #{Time.now.strftime '%S'}"
set_timeout 2000 do
puts "second #{Time.now.strftime '%S'}"
end
puts "third #{Time.now.strftime '%S'}"
set_timeout 1000 do
puts "fourth #{Time.now.strftime '%S'}"
end
# sleep 3
end
# >> first: 22
# >> third 22
# >> fourth 23
# >> second 24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment