Skip to content

Instantly share code, notes, and snippets.

@apeiros
Last active August 29, 2015 14:04
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 apeiros/500d3188a81f133f1df9 to your computer and use it in GitHub Desktop.
Save apeiros/500d3188a81f133f1df9 to your computer and use it in GitHub Desktop.
Recreate a browser's run-loop
# The code ported to ruby
results = []
rounds = 5
callback = (result) ->
results.push result
if results.length is rounds
console.log "All #{rounds} requests have completed! Here they are:", results
[1 .. rounds].forEach (item) ->
setTimeout (-> callback(item)), item * 1000
console.log "This line should appear on top of the output"
require 'runner'
Runner.new do
results = []
rounds = 5
callback = ->(result) {
results.push result
if results.size == rounds
puts "All #{rounds} requests have completed! Here they are:", *results
end
}
1.upto(rounds) do |item|
timeout 0 do callback.call(item) end
end
puts "This line should appear on top of output"
end
class Runner
Delayed = Struct.new(:id, :execute_at, :reschedule, :work) do
def <=>(other)
execute_at <=> other.execute_at
end
end
def initialize(&block)
@id = 0
@delayed = []
if block
instance_eval(&block)
run
end
end
def timeout(milliseconds, &work)
@delayed << Delayed.new(@id+=1, Time.now+milliseconds.fdiv(1000), nil, work)
@delayed.sort!
end
def intervall(milliseconds, &work)
@delayed << Delayed.new(@id+=1, Time.now+milliseconds.fdiv(1000), milliseconds, work)
@delayed.sort!
end
def clear_timeout(id)
@delayed.delete_at(@delayed.find_index { |work| work.id == id })
end
def run
until @delayed.empty?
delayed = @delayed.shift
delayed.work.call
if delayed.reschedule
delayed.execute_at = Time.now+delayed.reschedule.fdiv(1000)
@delayed << delayed
@delayed.sort!
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment